poi操作docx替换${}占位符不成功的解决方法

替换模板文件中的${}占位符代码如下:

    String templatePath = "templates/fileContractApp/pxhtdj/??.docx"; //模板文件存放路径
	String fileName="??.docx";                                              // 文件名
	
	XwpfTUtil xwpfUtil = new XwpfTUtil();
	ClassPathResource resource = new ClassPathResource(templatePath);
	InputStream is = resource.getInputStream();
	XWPFDocument doc = new XWPFDocument(is);
	Map<String, String> map = new HashedMap<String, String>();
	map.put("companyNameA", "??g公司");		      //甲方公司名称
	map.put("companyNameB", "??g公司");		      //乙方公司名称	
	map.put("field31", "???");				 
	map.put("field32", "???");				 
	map.put("field33", "???");				  
	map.put("field34", "???");				  。
	map.put("field35", "???");				  
	map.put("field36", "???");
	
	//获取模板中的表格 
	List<XWPFTable> tables = doc.getTables();                                     
	//存放table替换数据
	Map<String, String> itemMap = new HashedMap<String, String>();
	//合同模板文件中的表格部分内容赋值
	itemMap.put("${companyNameA}", "??g公司");    //甲方公司名称
	itemMap.put("${companyNameB}", "??g公司");    //乙方公司名称
	// 循环所有table替换数据
	for (int i = 0; i < tables.size(); i++) {
		XWPFTable tableXS = tables.get(i);
		for (int j = 0; j < tableXS.getRows().size(); j++) {
			for (int h = 0; h < tableXS.getRows().get(j).getTableCells().size(); h++) {
				for (int k = 0; k < tableXS.getRows().get(j).getTableCells().get(h).getParagraphs().size(); k++) {
					XWPFParagraph para = tableXS.getRows().get(j).getTableCells().get(h).getParagraphs().get(k);
					setParaValu1(para, itemMap);
				}
			}
		}
	}
	WorderToNewWordUtils.changeText(doc, map);//解析替换文本段落对象
	ByteArrayOutputStream b = new ByteArrayOutputStream();
	doc.write(b); 
	InputStream inputStream = new ByteArrayInputStream(b.toByteArray());
	Map<String, String> mapDescriptions = new HashedMap<String, String>();
	mapDescriptions.put("filename", fileName);
	String filePath = fastDFSClient.upload(inputStream, fileName, mapDescriptions);//上传文件服务器
	//关闭
	doc.close();
    xwpfUtil.close(is);

替换不成功,解决方法如下:
1、首先打开docx文件,另存为xml文件。
2、用文本编辑器打开保存的xml文件,搜索$,删除掉带格式的占位符,删除成 跟模板文件中相同的格式。然后保存。
3、用word打开保存的xml文件,另存为.docx格式。
4、使用新保存的.docx文件即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值