公司有個(gè)生成合同內(nèi)容的需求筷转,需要近期完成,于是找了度娘整理了一下。
引入pom依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
首先得準(zhǔn)備一下模板文件
image.png
讀取解析文件
InputStream in = null;
try {
in = new FileInputStream(templatePath);
//獲取docx解析對(duì)象
document = new XWPFDocument(in);
document.close();
}catch (Exception e){
e.printStackTrace();
}
解析段落標(biāo)簽
/**
* 替換段落文本
*
* @param document docx解析對(duì)象
* @param textMap 需要替換的信息集合
*/
public static void changeText(XWPFDocument document, Map<String, String> textMap) {
//獲取段落集合
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
//獲取到段落中的所有文本內(nèi)容
String text = paragraph.getText();
}
}
判斷是否需要替換內(nèi)容
/**
* 判斷文本中是否包含$
*
* @param text 文本
* @return 包含返回true, 不包含返回false
*/
public static boolean checkText(String text) {
boolean check = false;
if (text.indexOf("$") != -1) {
check = true;
}
return check;
}
根據(jù)map內(nèi)容替換參數(shù)
/**
* 匹配傳入信息集合與模板
*
* @param value 模板需要替換的區(qū)域
* @param textMap 傳入信息集合
* @return 模板需要替換區(qū)域信息集合對(duì)應(yīng)值
*/
public static String changeValue(String value, Map<String, String> textMap) {
System.out.println("value::"+value+"::");
String mapKey=value.trim().replace("${","").replace("}","");
String mapValue=textMap.get(mapKey);
if(StringUtils.isNotEmpty(mapValue)){
value =" "+mapValue+" ";//value.replace("${"+mapKey+"}",mapValue);
}
//模板未匹配到區(qū)域替換為空
if (checkText(value)) {
value = "";
}
return value;
}
# 替換模板內(nèi)容
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
//替換模板原來(lái)位置
run.setText(changeValue(run.toString(), textMap), 0);
}
保存文件
File dest = (new File(fileName)).getCanonicalFile();
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
changeText(document, replaceMap);
document.write(new FileOutputStream(dest));
運(yùn)行查看效果
image.png