import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by zhangjun on 16/2/21.
*/
public class DocUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DocUtil.class);
private static final DocUtil UTIL = new DocUtil();
/**
* 使用参数填充word文档
*
* @param map
*/
public static XWPFDocument fill(Map map){
String filePath = DocUtil.class.getResource("/template.docx").getPath();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
LOGGER.error("模版文件未找到:"+e.getMessage());
}
XWPFDocument document = null;
try {
document = new XWPFDocument(inputStream);
} catch (IOException e) {
LOGGER.error("读取word文档失败:"+e.getMessage());
}
UTIL.replaceInPara(document, map);
UTIL.replaceInTable(document, map);
return document;
}
/**
* 替换段落里面的变量
*
* @param doc 要替换的文档
* @param params 参数
*/
private void replaceInPara(XWPFDocument doc, Map params) {
Iterator iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params);
}
}
/**
* 替换段落里面的变量
*
* @param para 要替换的段落
* @param params 参数
*/
private void replaceInPara(XWPFParagraph para, Map params) {
List runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
int size = runs.size();
for (int i = 0; i < size; i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
matcher = this.matcher(runText);
if (matcher.find()) {
while ((matcher = this.matcher(runText)).find()) {
runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
}
run.setText(runText,0);
}
}
}
}
/**
* 正则匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
/**
* 替换表格里面的变量
*
* @param doc 要替换的文档
* @param params 参数
*/
private void replaceInTable(XWPFDocument doc, Map params) {
Iterator iterator = doc.getTablesIterator();
XWPFTable table;
List rows;
List cells;
List paras;
while (iterator.hasNext()) {
table = iterator.next();
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params);
}
}
}
}
}
}