今天给大家带来一个Apache-POI的Word解析工具。
public class WordTemplateParse {
public static Boolean generate(Map<String, String> data, InputStream tempFileStream, OutputStream targetFileStream) {
try {
// 加载磁盘的 temp.docx 文件
XWPFDocument document = new XWPFDocument(tempFileStream);
// 解析文档中的【段落】的插值 ${..}
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
String text = paragraph.getText();
// 如果该单元格为空就遍历下一个
if (text == null || "".equals(text)) {
continue;
}
// 得到解析 ${...} 后的内容
String newText = replaceByMap(text, null, data);
// 判断值是否改变,如果没有改变就不做处理
if (!text.equals(newText)) {
int runSize = paragraph.getRuns().size();
// 清空该段落所有值
for (int i = 0; i < runSize; i++) {
paragraph.removeRun(i);
}
XWPFRun run = paragraph.createRun();
run.setText(newText);
}
}
// 解析文档中【表格】的插值 ${..}
// 获取文档中的表格
List<XWPFTable> tables = document.getTables();
for (XWPFTable table : tables) {
// 得到所有行的集合并遍历
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
// 得到所有列的集合并遍历
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
// 获取整个单元格的值
String text = cell.getText();
// 如果该单元格为空就遍历下一个
if (text == null || "".equals(text)) {
continue;
}
// 得到解析 ${...} 后的内容
String newText = replaceByMap(text, null, data);
// 判断值是否改变,如果没有改变就不做处理
if (!text.equals(newText)) {
// 清空单元格内容
int paragraphsNums = cell.getParagraphs().size();
for (int i = 0; i < paragraphsNums; i++) {
cell.removeParagraph(i);
}
cell.setText(newText);
}
}
}
}
// 将文档写入目标文件中
document.write(targetFileStream);
// 关闭流
tempFileStream.close();
targetFileStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 如果根据正则表达式规则匹配成功则替换,否则返回原值
private static String replaceByMap(String content, String regex, Map<String, String> map) {
// 匹配插值 ${...}
if (regex == null) {
regex = "\\$\\{[\\w\\W]+\\}";
}
// 初始化正则
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(content);
// 找到匹配的内容的 key
if (matcher.find()) {
// 提前key值
String matchContent = matcher.group(0);
int start = matchContent.indexOf("{");
int end = matchContent.indexOf("}");
// 获取key
String key = matchContent.substring(start + 1, end);
// 从map中取出key的值
String value = map.get(key);
if (value == null) {
return content;
}
// 得到替换后的值
String newContent = matcher.replaceAll(value);
return newContent;
}
// 没有匹配到,返回原值
return content;
}
}
编写一个测试类:
@Test
public void test01() throws FileNotFoundException {
// 数据
TreeMap<String, String> data = new TreeMap<String, String>();
data.put("id", "0001");
data.put("number", "2");
data.put("date", "2020-10-21");
data.put("payee", "张三");
data.put("user_of_payment", "设备维修");
data.put("capitalization_amount", "壹佰元整");
data.put("lowercase_amount", "100");
data.put("title", "这是凭据的标题==测试");
data.put("footer", "这是底部的一段文本==测试");
// 加载模型【模型】
FileInputStream fis = new FileInputStream("src/main/resources/temp.docx");
// 输出位置【输出】
FileOutputStream fos = new FileOutputStream("src/main/resources/new_temp.docx");
Boolean generate = WordTemplateParse.generate(data, fis, fos);
System.out.println(generate);
}
- 这是一个Word的模板:
- 这是工具解析${…}后的样子:
源代码分享
链接:https://pan.baidu.com/s/1U1E9frZeIb9dOVCM1XWL2Q
提取码:nlqd