美文网首页
poi 使用word模板生成多页word文档(无替换图片方法)

poi 使用word模板生成多页word文档(无替换图片方法)

作者: 三没产品 | 来源:发表于2019-12-11 17:00 被阅读0次

主方法

注意:dataList 里的map必须包含要替换的所有参数,如果为null,则无法替换

参考地址: https://www.jianshu.com/p/6603b1ea3ad1

public void export(List<Map> dataList, HttpServletResponse baseResponse) {
        try (OutputStream out = baseResponse.getOutputStream()){
            // 设定输出文件头
            baseResponse.setHeader("Content-disposition ",
                "attachment; filename="
                    + URLEncoder.encode("template"
                    + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()), "utf-8")
                    + ".docx ");
            XWPFDocument xwpfDocument = null;
            for (Map map : dataList) {
                XWPFDocument xwpfDocument1 = new XWPFDocument(this.getClass().getResourceAsStream("/doc_template/score.docx"));
                this.replaceInPara(xwpfDocument1,map);
                this.replaceInTable(xwpfDocument1,map);
                if (xwpfDocument == null) {
                    xwpfDocument = xwpfDocument1;
                }else {
                    this.mergeWord(xwpfDocument,xwpfDocument1);
                }
            }
            xwpfDocument.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

替换段落里面的变量

 /**
     * 替换段落文本
     * @param document docx解析对象
     * @param textMap 需要替换的信息集合
     */
    public static void changeText(XWPFDocument document, Map<String, String> textMap){
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        
        for (XWPFParagraph paragraph : paragraphs) {
            //判断此段落时候需要进行替换
            String text = paragraph.getText();
            if(checkText(text)){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //替换模板原来位置
                    run.setText(changeValue(run.toString(), textMap),0);
                }
            }
        }
    }

替换表格里面的变量

 /**
     * 判断文本中时候包含$
     * @param text 文本
     * @return 包含返回true,不包含返回false
     */
    public static boolean checkText(String text){
        boolean check  =  false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;
    }

    /**
     * 匹配传入信息集合与模板
     * @param value 模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public static String changeValue(String value, Map<String, String> textMap){
        Set<Map.Entry<String, String>> textSets = textMap.entrySet();
        for (Map.Entry<String, String> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = "${"+textSet.getKey()+"}";
            if(value.indexOf(key)!= -1){
                value = textSet.getValue();
            }
        }
        //模板未匹配到区域替换为空
        if(checkText(value)){
            value = "";
        }
        return value;
    }

    /**
     * 遍历表格
     * @param rows 表格行对象
     * @param textMap 需要替换的信息集合
     */
    public static void eachTable(List<XWPFTableRow> rows ,Map textMap){
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判断单元格是否需要替换
                if(checkText(cell.getText())){
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            run.setText(changeValue(run.toString(), textMap),0);
                        }
                    }
                }
            }
        }
    }

    /**
     * 替换表格里面的变量
     * @param doc 要替换的文档
     * @param params 参数
     */
    public void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
        //获取表格对象集合
        List<XWPFTable> tables = doc.getTables();
        for (int i = 0; i < tables.size(); i++) {
            //只处理行数大于等于2的表格,且不循环表头
            XWPFTable table = tables.get(i);
            if(table.getRows().size()>1){
                //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
                if(checkText(table.getText())){
                    List<XWPFTableRow> rows = table.getRows();
                    //遍历表格,并替换模板
                    eachTable(rows, params);
                }
            }
        }
    }

两个对象进行追加(即把新生成的文档追加到已有文档里)

/**
     * 两个对象进行追加
     * @param document
     * @param doucDocument2
     * @return
     * @throws Exception
     */
    public  XWPFDocument mergeWord(XWPFDocument document,XWPFDocument doucDocument2) throws Exception {
        XWPFDocument src1Document =document ;
        XWPFParagraph p = src1Document.createParagraph();
        //设置分页符
        p.setPageBreak(true);
        CTBody src1Body = src1Document.getDocument().getBody();
        XWPFDocument src2Document = doucDocument2;
        CTBody src2Body = src2Document.getDocument().getBody();
        XWPFParagraph p2 = src2Document.createParagraph();
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = src2Body.xmlText(optionsOuter);
        String srcString = src1Body.xmlText();
        String prefix = srcString.substring(0,srcString.indexOf(">")+1);
        String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
        String sufix = srcString.substring( srcString.lastIndexOf("<") );
        String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
        CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
        src1Body.set(makeBody);
        return src1Document;
    }

相关文章

网友评论

      本文标题:poi 使用word模板生成多页word文档(无替换图片方法)

      本文链接:https://www.haomeiwen.com/subject/oxqagctx.html