使用原生POI和EasyPoi根据word模板导出word工具类

1. 前言

前两天接了个需求,要求将数据导出成word,里边有边个,有其他的东西,怎么说这,这个需求最开始就是上传word,下载附件就行了,非得改成上传数据然后支持下载word。有股脱裤子放屁的感觉

而且呢,当时做的时候前任开发在数据库存了一个巨大的Json文件,解析也挺费劲的咱就是说。本来只为难前端,现在前后端全部为难一遍。

最终敲定了两版方案,都有这些许瑕疵

  1. 原生POI

这个方案吧,纯手撸,
根据word模板生成word的时候,表格内的文字无法设置行距1.0,首行缩进2字符无法取消,数字会换行。

  1. EasyPoi

相对简单一点,但是也有不小的问题,表格内的字体无法设置中文,行距首行缩进问题得到解决,
但是这个包读取模板文件有点问题,不过可以自行解决

  1. 修改docx的document.xml

用zip将docx解压出来改xml,怎么说呢,不是人能干的活,眼都能看瞎

2. 解决方案

1 原生POI

1. 引入依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
<!--导出word数据-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

2. 创建一个word模板

就类似下边这样的一个模板,最开始用{companyName}这样的占位符,结果原生poi给我的这个占位符识别成了三个段落,后来就改成这样了

image-20240124105715551

3. 准备数据

我的数据存在一个巨大的json里边,要是其他的数据可以改造下边的fillTableData方法

{
   
   
	"companyName": "测试",
	"startTime": "2024-01-24",
	"endTime": "2024-01-31",
	"content": "{\"companyName\":\"测试\",\"userList\":[{\"id\":1,\"name\":\"测试\",\"age\":18,\"birthDay\":\"1999-01-01\",\"hobby\":\"\",\"extra\":\"\"}]}"
}

4. 代码编写

package org.example;

import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.example.entity.ReportInfo;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author eleven
 * @date 2024/1/22 9:08
 * @apiNote
 */
@Slf4j
public class DocxTest {
   
   
    
    @Test
    public void test() {
   
   
        Gson gson = new Gson();
        // 从resources下获取文件数据
        ClassPathResource resource = new ClassPathResource("response.json");
        ClassPathResource docxResource = new ClassPathResource("word模板.docx");

        try (InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
             XWPFDocument document = new XWPFDocument(docxResource.getInputStream());
             FileOutputStream fos = new FileOutputStream("e:\\output.docx")
        ){
   
   
            ReportInfo reportInfo = gson.fromJson(inputStreamReader, ReportInfo.class);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 获取文档的所有段落
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            Map reportInfoMap = getReportInfo(reportInfo);
            replaceRegex(paragraphs, "companyName", String.valueOf(reportInfoMap.get("companyName")));
            replaceRegex(paragraphs, "startTime", sdf.format(reportInfo.getStartTime()));
            replaceRegex(paragraphs, "endTime", sdf.format(reportInfo.getEndTime()));
            // 获取所有表格
            List<XWPFTable> tables = document.getTables();
            fillTableData(tables.get(0),
                    getTableData(reportInfoMap,
                            "userList",
                            "id",
                            "name",
                            "age",
                            "birthDay",
                            "hobby",
                            "extra"
                    )
            );
            document.write(fos);
        } catch (IOException e) {
   
   
            throw new RuntimeException(e);
        }
    }
	
    /**
     * 获取表格的数据
     * @param reportInfoMap         map数据
     * @param key                   json数据中的key    
     * @param sortedCellKey         表格中排序好的cell表格字段
     * @return List<List<String>>   表格中每一行的数据
     */
    @SuppressWarnings("unchecked")
    private List<List<String>> getTableData(Map reportInfoMap, String key, String... sortedCellKey) {
   
   
        Object data = reportInfoMap.get(key);
        if (data instanceof List) {
   
   
            List<Map> dataList = (List<Map>)data;
            List<List<String>> result = new ArrayList<>(dataList.size());
            List<String> rowData = new ArrayList<>(sortedCellKey.length);
            for (Map map : dataList) {
   
   
                for (String cellKey : sortedCellKey) {
   
   
                    if (StrUtil.equalsAnyIgnoreCase("id", cellKey)) {
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值