使用POI替换docx模板生成docx

2021-12-07 20:51:02 浏览数 (2)

发表于2017-10-112019-01-01 作者 wind

代码语言:javascript复制
/*
 * Copyright (c) 2017 西安才多信息技术有限责任公司。
 * 项目名称:dev
 * 文件名称:DocxTemplateUtils.java
 * 日期:17-10-11 下午2:18
 * 作者:yangyan
 *
 */

package cn.firegod.common.utils;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

public class DocxTemplateUtils {

    private final Map<String, Object> params;
    String filePath;
    InputStream is;
    XWPFDocument doc;

    public DocxTemplateUtils(String templateDocxFile, Map<String, Object> params) {
        this.filePath = templateDocxFile;
        this.params = params;

        try {
            is = new FileInputStream(filePath);
            doc = new XWPFDocument(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 此类为poi操作word模板的工具类
     *
     * @Author qixin at 2017-6-01
     */


    public XWPFDocument getDoc() {
        return doc;
    }

    /**
     * 替换段落里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数
     */
    public void replaceInPara() {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            this.replaceInPara(para);
        }
    }

    /**
     * 替换段落里面的变量
     *
     * @param para   要替换的段落
     * @param params 参数
     */
    public void replaceInPara(XWPFParagraph para) {
        List<XWPFRun> runs;
        Matcher matcher;

        runs = para.getRuns();

        int start = -1;
        int end = -1;
        String str = "";
        for (int i = 0; i < runs.size(); i  ) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
//            System.out.println("------>>>>>>>>>"   runText);
            if ('$' == runText.charAt(0)) {
                start = i;
            }
            if ((start != -1)) {
                str  = runText;
            }
            if ('}' == runText.charAt(runText.length() - 1)) {
                if (start != -1) {
                    end = i;
                    break;
                }
            }
        }
//        System.out.println("start--->"   start);
//        System.out.println("end--->"   end);

//        System.out.println("str---->>>"   str);

        for (int i = start; i <= end; i  ) {
            para.removeRun(i);
            i--;
            end--;
//            System.out.println("remove i="   i);
        }

        for (String key : params.keySet()) {
            if (str.equals(key)) {
                Object o = params.get(key);
                if (o instanceof List) {
                    List oList = (List) o;
                    XWPFNumbering numbering = doc.createNumbering();
                    int size = oList.size();
                    for (int i = 0; i < size; i  ) {
                        Object o1 = oList.get(i);
                        XWPFRun run = para.createRun();
                        run.setText((String) o1);
                        if (i   1 < size) {
                            run.addBreak();
                        }
                    }
                } else {
                    para.createRun().setText((String) o);
                }
                break;
            }
        }
    }

    /**
     * 替换表格里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数
     */
    public void replaceInTable() {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            rows = table.getRows();
            for (XWPFTableRow row : rows) {
                cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    paras = cell.getParagraphs();
                    for (XWPFParagraph para : paras) {
                        this.replaceInPara(para);
                    }
                }
            }
        }
    }

    /**
     * 关闭输入流
     *
     * @param is
     */
    public void closeInputStream() {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     *
     * @param os
     */
    public void closeOutputStream(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

0 人点赞