poi动态填充word内容

java 复制代码
package com.shiting.analysis.util;

import com.alibaba.fastjson.JSON;
import com.shiting.analysis.model.dto.TemplateDto;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ToDocUtils {
    //使用示例
    public static void main(String[] args) throws Exception {
        TemplateDto dto = new TemplateDto();
        dto.setProband_name("aaa");
        dto.setProband_NO("1111111");
        dto.setPhone("1212121212");
        dto.setAge_F("45");
        dto.setAge_M("13");
        dto.setReceive_date("2022.1.1");
        dto.setReport_date("2023.100");
        dto.setClinical_info("dskds");
        dto.setMother_name("bbb");
        dto.setMother_NO("11111111");
        dto.setFather_name("cccc");
        dto.setFather_NO("111");
        dto.setGene_name("ddd");
        dto.setMain_conclusion("ddd");
        dto.setParents_or_not("ddd");
        dto.setMain_explanation("ddd");
        dto.setPast_description_main("ddd");
        dto.setMain_site_suggestion_1("应该1..");
        dto.setMain_site_suggestion_2("应该2.。");
        dto.setSeq_info("111");
        dto.setReport_D_B("20231117");
        dto.setPicture_title("dsdsd");
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(dto), Map.class);
        String templatePath = "C:\\code\\genomic-analysis-backend\\src\\main\\resources\\positive_template有主位点阳性.docx";
        String outPath = "C:\\code\\genomic-analysis-backend\\src\\test\\java\\com\\shiting\\analysis\\out.docx";
        getDocx(templatePath , outPath , map);
    }
    /**
     * 导出docx
     * @param templatePath
     * @param outPath
     * @param map
     */
    public static boolean  getDocx(String templatePath, String outPath, Map<String, Object> map){
        XWPFDocument document = null;
        try{
            File file = new File(templatePath);
            InputStream in = new FileInputStream(file);
            document = new XWPFDocument(in);

            //替换页眉变量
            Iterator<XWPFHeader> headerIterator = document.getHeaderList().iterator();
            while (headerIterator.hasNext()){
                XWPFHeader header = headerIterator.next();
                replaceHeader(header,map);
            }
            //替换页脚变量
            Iterator<XWPFFooter> footerIterator = document.getFooterList().iterator();
            while (footerIterator.hasNext()){
                XWPFFooter footer = footerIterator.next();
                replaceFooter(footer,map);
            }
            //替换表格里面的变量
            replaceInTable(document,map);
            //替换段落里的
            Iterator<XWPFParagraph> paragraphIterator = document.getParagraphs().iterator();
            while (paragraphIterator.hasNext()){
                XWPFParagraph paragraph = paragraphIterator.next();
                replaceParagraph(paragraph,map);
            }
            // 如果文件夹不存在 则建立新文件夹
            File dir= new File(outPath);
            if (!dir.exists() == false) {
                dir.mkdirs();
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            OutputStream out = new FileOutputStream(outPath);
            document.write(bos);
            out.write(bos.toByteArray());
            bos.close();
            out.close();
            return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        } finally{
            try
            {
                if ( document != null )
                {
                    document.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 替换段落里面的变量
     * @param paragraph
     * @param map
     */
    public static void replaceParagraph(XWPFParagraph paragraph, Map<String,Object> map){
        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String tkey = run.toString();
            if(tkey==null){
                return;
            }
            for (String key : map.keySet()) {
                if(tkey.equals(key)){
                    int size = run.getFontSize();
                    if(size==-1){
                        size=14;
                    }
                    String fontFamily = run.getFontFamily();
                    //因为直接调用setText()方法替换文本时,会在底层重新创建一个run,所以在设置文本之前要先删除当前run
                    paragraph.removeRun(i);
                    if(map!=null && map.get(key)!=null){
                        String runText = map.get(key).toString();
                        if(runText!=null){
                            if(runText.indexOf("\r\n")!=-1){
                                String[] texts = runText.split("\r\n");
                                List<String> tmp = new ArrayList<>();
                                for (String text : texts) {
                                    if(text!=null && text.length()!=0){
                                        tmp.add(text);
                                    }
                                }
                                texts = tmp.toArray(new String[0]);
                                for (int n = 0; n < texts.length; n++) {
                                    XWPFRun newRun = paragraph.createRun();
                                    newRun.setText("    "+texts[n].trim());
                                    if(texts.length>1 && n!=texts.length-1){
                                        newRun.addBreak();
                                    }
                                    newRun.setText(runText);
                                    newRun.setFontSize(size);
                                    newRun.setFontFamily(fontFamily);
                                }
                            }else if(runText.indexOf("\n")!=-1){
                                String[] texts = runText.split("\n");
                                List<String> tmp = new ArrayList<>();
                                for (String text : texts) {
                                    if(text!=null && text.length()!=0){
                                        tmp.add(text.trim());
                                    }
                                }
                                texts = tmp.toArray(new String[0]);
                                for (int n = 0; n < texts.length; n++) {
                                    XWPFRun newRun = paragraph.createRun();
                                    newRun.setText("    "+texts[n].trim());
                                    if(texts.length>1 && n!=texts.length-1){
                                        newRun.addBreak();
                                    }
                                    newRun.setFontSize(size);
                                    newRun.setFontFamily(fontFamily);
                                }
                            }else{
                                //重新创建一个run用于设置文本
                                XWPFRun newrun = paragraph.insertNewRun(i);
                                newrun.setText(runText);
                                newrun.setFontSize(size);
                                newrun.setFontFamily(fontFamily);
                            }
                        }
                    }
                }
            }
        }
    }
    public static void replaceFooter(XWPFFooter Footer, Map<String,Object> map){
        //获取表
        List<XWPFTable> tableList = Footer.getTables();
        if(tableList!=null && tableList.size()>0){
            for (int i = 0; i < tableList.size(); i++) {
                XWPFTable table = tableList.get(i);
                //获取行
                List<XWPFTableRow> rows = table.getRows();
                //获取单元格
                for (XWPFTableRow row : rows) {
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        //获取段落
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();
                        for (XWPFParagraph paragraph : paragraphs) {
//                            paragraph.setAlignment(ParagraphAlignment.LEFT);
                            replaceParagraph(paragraph,map);
                        }
                    }
                }
            }
        }
        else {
            List<XWPFParagraph> paragraphs = Footer.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
//                paragraph.setAlignment(ParagraphAlignment.LEFT);
                replaceParagraph(paragraph,map);
            }
        }
    }
    /**
     * 替换页眉里面的变量
     * @param Header
     * @param map
     */
    public static void replaceHeader(XWPFHeader Header, Map<String,Object> map){
        //获取表
        List<XWPFTable> tableList = Header.getTables();
        if(tableList!=null && tableList.size()>0){
            for (int i = 0; i < tableList.size(); i++) {
                XWPFTable table = tableList.get(i);
                //获取行
                List<XWPFTableRow> rows = table.getRows();
                for (XWPFTableRow row : rows) {
                    //获取单元格
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        //获取单元格内容
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();
                        for (XWPFParagraph paragraph : paragraphs) {
//                            paragraph.setAlignment(ParagraphAlignment.LEFT);
                            replaceParagraph(paragraph,map);
                        }
                    }
                }
            }
        }
        else {
            List<XWPFParagraph> paragraphs = Header.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
//                paragraph.setAlignment(ParagraphAlignment.LEFT);
                replaceParagraph(paragraph,map);
            }
        }

    }
    /**
     * 替换表格里面的变量
     * @param document
     * @param map
     */
    public static void replaceInTable(XWPFDocument document, Map<String,Object> map) throws Exception {
        Iterator<XWPFTable> iterator = document.getTablesIterator();
        while (iterator.hasNext()){
            //获取表
            XWPFTable table = iterator.next();
            //获取行
            List<XWPFTableRow> rows = table.getRows();
            for (XWPFTableRow row : rows) {
                //获取单元格
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        //paragraph.setAlignment(ParagraphAlignment.LEFT);
                        replaceParagraph(paragraph,map);
                    }
                }
            }
        }
    }
}
相关推荐
2401_8574396923 分钟前
SpringBoot框架在资产管理中的应用
java·spring boot·后端
怀旧66625 分钟前
spring boot 项目配置https服务
java·spring boot·后端·学习·个人开发·1024程序员节
李老头探索26 分钟前
Java面试之Java中实现多线程有几种方法
java·开发语言·面试
芒果披萨32 分钟前
Filter和Listener
java·filter
qq_49244844636 分钟前
Java实现App自动化(Appium Demo)
java
阿华的代码王国1 小时前
【SpringMVC】——Cookie和Session机制
java·后端·spring·cookie·session·会话
找了一圈尾巴2 小时前
前后端交互通用排序策略
java·交互
哎呦没4 小时前
SpringBoot框架下的资产管理自动化
java·spring boot·后端
m0_571957586 小时前
Java | Leetcode Java题解之第543题二叉树的直径
java·leetcode·题解
魔道不误砍柴功8 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python