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);
  }
相关推荐
zfoo-framework5 分钟前
【jenkins插件】
java
风_流沙10 分钟前
java 对ElasticSearch数据库操作封装工具类(对你是否适用嘞)
java·数据库·elasticsearch
ProtonBase40 分钟前
如何从 0 到 1 ,打造全新一代分布式数据架构
java·网络·数据库·数据仓库·分布式·云原生·架构
乐之者v1 小时前
leetCode43.字符串相乘
java·数据结构·算法
suweijie7684 小时前
SpringCloudAlibaba | Sentinel从基础到进阶
java·大数据·sentinel
公贵买其鹿5 小时前
List深拷贝后,数据还是被串改
java
xlsw_8 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹9 小时前
基于java的改良版超级玛丽小游戏
java
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭9 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫9 小时前
泛型(2)
java