替换模板文件中的${}占位符代码如下:
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文件即可。