java中,通过替换word模板中的关键字后输出一个新文档

一、要用到的jar包

我已上传了相关的jar包,需要的可以通过以下链接直接下载:

https://download.csdn.net/download/qq_27387133/88558034

具体jar包截图:

二、实现的代码

注意:文件要用docx格式!!!

word变量替换的方法(replaceWord):

/**    
	 * @Description: TODO word替换变量的方法
	 * @author: zgx 
	 * @date:   2023年11月20日 下午3:03:42
	 * @param srcPath 模板路径
	 * @param destPath 输出路径
	 * @param map 替换的变量值集合
	 * @return      
	 * @return: boolean       
	 */
	public static boolean replaceWord(String srcPath,String destPath, HashMap<String, Object> map) {
        try {
            // 替换的的关键字存放到Set集合中
            Set<String> set = map.keySet();
            // 读取模板文档
            XWPFDocument document = new XWPFDocument(new FileInputStream(srcPath));
            /**
             * 替换段落中的指定文字
             */
            // 读取文档中的段落,回车符为一个段落。
            // 同一个段落里面会被“:”等符号隔开为多个对象
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                // 获取文档中当前的段落文字信息
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                List<XWPFRun> run = paragraph.getRuns();
                // 遍历段落文字对象
                for (int i = 0; i < run.size(); i++) {
                    // 获取段落对象
                    if (run.get(i) == null) {	//段落为空跳过
                        continue;
                    }
                    String sectionItem = run.get(i).getText(run.get(i).getTextPosition());	//段落内容
                    // 遍历自定义表单关键字,替换Word文档中的内容
                    Iterator<String> iterator = set.iterator();
                    while (iterator.hasNext()) {
                        // 当前关键字
                        String key = iterator.next();
                        // 替换内容
                        sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                    }
                    run.get(i).setText(sectionItem, 0);
                }
            }

            /**
             * 替换表格中的指定文字
             */
            //获取文档中所有的表格,每个表格是一个元素
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();   //获取表格内容
                int count = table.getNumberOfRows();    //表格的行数
                //遍历表格行的对象
                for (int i = 0; i < count; i++) {
                    XWPFTableRow row = table.getRow(i);    //表格每行的内容
                    List<XWPFTableCell> cells = row.getTableCells();   //每个单元格的内容
                    //遍历表格的每行单元格对象
                    for (int j = 0; j < cells.size(); j++) {
                        XWPFTableCell cell = cells.get(j);	//获取每个单元格的内容
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();      //获取单元格里所有的段落
                        for (XWPFParagraph paragraph : paragraphs) {
                            //获取段落的内容
                            List<XWPFRun> run = paragraph.getRuns();
                            // 遍历段落文字对象
                            for (int o = 0; o < run.size(); o++) {
                                // 获取段落对象
                                if (run.get(o) == null || run.get(o).equals("")) {
                                    continue;
                                }
                                String sectionItem = run.get(o).getText(run.get(o).getTextPosition());	//获取段落内容
                                if (sectionItem == null || sectionItem.equals("")) {	//段落为空跳过
                                    continue;
                                }
                                //遍历自定义表单关键字,替换Word文档中表格单元格的内容
                                for (String key : map.keySet()) {
                                    // 替换内容
                                    sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                                    run.get(o).setText(sectionItem, 0);


                                }
                            }
                        }
                    }
                }
            }
//            设置word不可编辑
//            document.enforceFillingFormsProtection("123", HashAlgorithm.sha512);
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

具体地方调用replaceWord方法示例:

public void doReplaceWord(){
    
				String newPath = 路径+"你的新文件.docx";
				String oldPath = 路径+"你的模板文件.docx";
				
				HashMap<String, Object> resultMap = new HashMap<>();
		        //简历名称
				resultMap.put("${resumeName}","我的简历");
				//创建时间
				resultMap.put("${createTime}","2023-10-10");
				//最后修改时间
				resultMap.put("${updateTime}","2023-11-10");				
				
		        replaceWord(oldPath, newPath, resultMap);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MrZhouGx

觉得对你有用的话可以支持一下

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值