美文网首页
[原创] Java poi替换模板

[原创] Java poi替换模板

作者: 韩朝阳 | 来源:发表于2020-06-23 10:18 被阅读0次

    设置替换内容Map(也可以通过反射根据字段名从实体类中获取字段值)

    // data为实体类
    HashMap<String, String> valueMap = new HashMap<>();
    
    valueMap.put("#{name}", data.getName());
    valueMap.put("#{unit}", data.getUnit());
    valueMap.put("#{post}", data.getPost());
    valueMap.put("#{phone}", data.getPhone());
    

    设置提取占位符的正则表达式

    // 该表达式可提取#{xxx}占位符
    private static final String REG_EX = "#\\{.*?\\}";
    

    遍历模板表格替换

    // xxx.docx为模板路径
    XWPFDocument document = new XWPFDocument(new FileInputStream(new File("xxx.docx")));
    // 表格序号,从0开始
    int n = 0;
    XWPFTable table = document.getTables().get(n);
    List<XWPFTableRow> rows = table.getRows();
    for (int r = 0; r < rows.size(); r++) {
        XWPFTableRow row = rows.get(r);
        List<XWPFTableCell> tableCells = row.getTableCells();
        for (int c = 0; c < tableCells.size(); c++) {
            XWPFTableCell cell = tableCells.get(c);
            XWPFParagraph paragraph = cell.getParagraphs().get(0);
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                Matcher matcher = pattern.matcher(text);
                while (matcher.find()) {
                    String placeholder = matcher.group();
                    text = text.replace(placeholder, valueMap.get(placeholder));
                    run.setText(text, 0);
                }
            }
        }
    }
    
    try {
        // yyy.docx为文件输出路径
        document.write(new FileOutputStream(new File("yyy.docx")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    if (document != null) {
        try {
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    相关文章

      网友评论

          本文标题:[原创] Java poi替换模板

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