真实工作项目Java使用apache.poi生成word

发布于:2024-07-11 ⋅ 阅读:(29) ⋅ 点赞:(0)

加油,新时代打工人!

将实体类利用poi转成Word文件
demo示例

package com.fqpais.util;

import com.fqpais.business.domain.TestReportTemplate;
import com.fqpais.common.utils.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
*@author wh
*@date 2024年05月24日8:59
 * 获取数据填充到word模板
*/
public class ReaderWord {

    private static final Logger log = LoggerFactory.getLogger(ReaderWord.class);

    public static void generateWordFromTemplate(String templatePath, String outputPath, List<TestReportTemplate> testReportTemplate) throws IOException {
        FileInputStream fis = new FileInputStream(templatePath);
        XWPFDocument doc = new XWPFDocument(fis);

        int userIndex = 0; // 用来追踪当前处理的用户索引
        for (XWPFParagraph p : doc.getParagraphs()) {
            for (XWPFRun r : p.getRuns()) {
                String text = r.getText(0);
                if (text != null) {
                    text = replaceUserData(text, testReportTemplate.get(userIndex));
                    r.setText(text, 0);
                }
            }

        }

        // 处理表格
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph para : cell.getParagraphs()) {
                        for (XWPFRun run : para.getRuns()) {
                            String text = run.getText(0);
                            if (text != null) {
                                text = replaceUserData(text, testReportTemplate.get(userIndex));
                                run.setText(text, 0);
                            }
                        }
                    }
                }
            }
            // 同样,处理完一个表格后可能需要切换到下一个用户的数据
            userIndex++;
//            if (userIndex >= testReportTemplate.size()) break; // 防止数组越界
        }

        FileOutputStream out = new FileOutputStream(outputPath);
        doc.write(out);
        out.close();
        doc.close();
        fis.close();
        log.info("Word生成完成");
    }

    // 简化的替换逻辑,实际应用可能需要更复杂的正则表达式匹配
    private static String replaceUserData(String text, TestReportTemplate testReportTemplate) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        String square = numberFormat.format(testReportTemplate.getFieldsSquare());

        Date getDate = testReportTemplate.getGetDate();
        Date realTestTime = testReportTemplate.getRealTestTime();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String strDate1 = sdf1.format(realTestTime);
        String strDate2 = sdf1.format(getDate);
        if(StringUtils.isNull(testReportTemplate.getFarmerName())){
            testReportTemplate.setFarmerName("/");
        }
        if(StringUtils.isNull(testReportTemplate.getCode())){
            testReportTemplate.setCode("/");
        }
        if(StringUtils.isNull(testReportTemplate.getFieldsSquare())){
            testReportTemplate.setFieldsSquare(0L);
        }
        if(StringUtils.isNull(testReportTemplate.getTestEnvironment())){
            testReportTemplate.setTestEnvironment("/");
        }
        if(StringUtils.isNull(testReportTemplate.getFarmerContact())){
            testReportTemplate.setFarmerContact("/");
        }
        if(StringUtils.isNull(testReportTemplate.getTadminRegion().getName())){
            testReportTemplate.getTadminRegion().setName("/");
        }
        if(StringUtils.isNull(testReportTemplate.getTestItems())){
            testReportTemplate.setTestItems("/");
        }
        if(StringUtils.isNull(testReportTemplate.getTestBasis())){
            testReportTemplate.setTestBasis("/");
        }
        if(StringUtils.isNull(testReportTemplate.getTestUseDevice())){
            testReportTemplate.setTestUseDevice("/");
        }
        if(StringUtils.isNull(testReportTemplate.getConclusion())){
            testReportTemplate.setConclusion("不作结论。");
        }
        return text
                .replace("{{farmerName}}", testReportTemplate.getFarmerName())
                .replace("{{code}}", testReportTemplate.getCode())
                .replace("{{fieldsSquare}}",square)
                .replace("{{getDate}}",strDate2)
                .replace("{{realTestTime}}",strDate1)
                .replace("{{farmerContact}}",testReportTemplate.getFarmerContact())
                .replace("{{name}}",testReportTemplate.getTadminRegion().getName())
                .replace("{{testEnvironment}}",testReportTemplate.getTestEnvironment())
                .replace("{{testItems}}",testReportTemplate.getTestItems())
                .replace("{{testBasis}}",testReportTemplate.getTestBasis())
                .replace("{{testUseDevice}}",testReportTemplate.getTestUseDevice())
                .replace("{{conclusion}}",testReportTemplate.getConclusion());
    }

}