SpringBoot使用EasyPoi根据模板导出word or pdf

1、导出效果

1.1 wrod

1.2 pdf

2、依赖

java 复制代码
        <!--word-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.3.0</version>
        </dependency>

        <!--pdf-->
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.0.3</version>
        </dependency>

2、工具类

java 复制代码
package com.skybird.iot.addons.productionManagement.qualityTesting.backend.util;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class EasyPoiUtil {

  /**
   * 根据模板导出word
   *
   * @param map 数据
   * @param url 模板地址
   * @param tempFile 临时模板文件
   */
  public static void exportWord(Map<String, Object> map, String url, File tempFile) {
    try {
      XWPFDocument doc = WordExportUtil.exportWord07(url, map);
      FileOutputStream fos = new FileOutputStream(tempFile);
      doc.write(fos);
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * word转pdf导出
   *
   * @param response
   * @param tempFile word文档文件
   */
  public static void wordToPdfExport(HttpServletResponse response, File tempFile) {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=name.pdf");
    try (InputStream docxInputStream = new FileInputStream(tempFile);
        OutputStream pdfOutputStream = response.getOutputStream()) {

      IConverter converter = LocalConverter.builder().build();
      converter
          .convert(docxInputStream)
          .as(DocumentType.DOCX)
          .to(pdfOutputStream)
          .as(DocumentType.PDF)
          .execute();

      // 通常不需要在这里调用 flush(),因为 execute()方法可能已经完成了它,但如果遇到特定问题,可以尝试调用它
      // pdfOutputStream.flush();

    } catch (Exception e) {
      // 设置适当的 HTTP 状态码和错误消息
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      // 可以在这里记录错误或向客户端发送错误消息(但注意,响应流可能已关闭)
      e.printStackTrace();
    } finally {
      // 清理临时文件
      if (!tempFile.delete()) {
        tempFile.deleteOnExit();
      }
    }
  }
}

3、模板

4、模板指令

5、接口

java 复制代码
  @RequestMapping("exportWord")
  public void exportWord(HttpServletResponse response) throws IOException {
    response.setContentType("application/msword");
    response.setHeader("Content-disposition", "attachment;filename=name.docx");
    OutputStream outputStream = response.getOutputStream();

    Map<String, Object> map = new HashMap<>();

    putBaseInfo(map);
    putList(map);

    String url =
        Objects.requireNonNull(getClass().getClassLoader().getResource("templates/export.docx"))
            .getPath();

    File tempFile = File.createTempFile("tempDoc", ".docx");

    EasyPoiUtil.exportWord(map, url, tempFile);

    InputStream in = new FileInputStream(tempFile);

    // 创建存放文件内容的数组
    byte[] buff = new byte[1024];
    // 所读取的内容使用n来接收
    int n;
    // 当没有读取完时,继续读取,循环
    while ((n = in.read(buff)) != -1) {
      // 将字节数组的数据全部写入到输出流中
      outputStream.write(buff, 0, n);
    }
    // 强制将缓存区的数据进行输出
    outputStream.flush();
    // 关流
    outputStream.close();
    in.close();
    tempFile.deleteOnExit();
  }

  @RequestMapping("exportPdf")
  public void exportPdf(HttpServletResponse response) throws IOException {
    Map<String, Object> map = new HashMap<>();

    putBaseInfo(map);
    putList(map);

    String url =
        Objects.requireNonNull(getClass().getClassLoader().getResource("templates/export.docx"))
            .getPath();

    File tempFile = File.createTempFile("tempDoc", ".docx");

    EasyPoiUtil.exportWord(map, url, tempFile);

    EasyPoiUtil.wordToPdfExport(response, tempFile);
  }

  private void putBaseInfo(Map<String, Object> map) {
    map.put("technology", "EasyPoi");
    map.put("person", "JueYue");
    map.put("time", "2024-09-27");
  }

  private void putList(Map<String, Object> map) {
    List<Map<String, String>> list = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      Map<String, String> map1 = new HashMap<>();
      map1.put("name", "星晨");
      map1.put("age", "20");

      list.add(map1);
    }

    map.put("list", list);
  }
相关推荐
夜月行者25 分钟前
如何使用ssm实现科技银行业务管理系统+vue
java·后端·ssm
严文文-Chris29 分钟前
【设计模式-解释模式】
java·设计模式
coffee_baby37 分钟前
状态模式原理剖析
java·ui·ajax·设计模式·状态模式
脚步的影子1 小时前
在Java中调用Python
java·开发语言
夜月行者1 小时前
如何使用ssm实现钢铁集团公司安全管理系统的构建与实现
java·后端·ssm
王哲晓1 小时前
第八章 实战:构建Tomcat镜像及发布
java·docker·tomcat
AAA 建材批发王哥(天道酬勤)1 小时前
ZooKeeper
java·zookeeper
RainbowSea1 小时前
八,MyBatis-Plus 的“多数据源”的连接操作(详细说明)
java·spring·mybatis
鹿又笑1 小时前
常用性能优化方法
java·性能优化·系统优化
扎克begod1 小时前
JAVA并发编程系列(13)Future、FutureTask异步小王子
java·开发语言·jvm