开头贴出参考文章地址:
http://blog.sina.com.cn/s/blog_885585cb0101gnz7.html
http://www.cnblogs.com/dreammyle/p/5159267.html
效果图:原docx文件
效果图:替换后的docx文件
maven依赖:
org.apache.poi
poi
3.16
org.apache.poi
poi-scratchpad
3.16
org.apache.poi
poi-ooxml
3.16
java代码:
package com.smh.test;
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class WordUtil {
public static void main(String[] args) throws IOException {
String srcPath = "D:\\a.docx";
String destPath = "D:\\a-" + System.currentTimeMillis() + ".docx";
InputStream in = new FileInputStream(srcPath);
FileOutputStream out = new FileOutputStream(destPath);
Map map = new HashMap<>();
map.put("${AGE}", "10777");
map.put("${NAME}", "99999");
replaceText(in, out, map);
in.close();
out.close();
}
public static void replaceText(InputStream inputStream, OutputStream outputStream, Map map) {
try {
XWPFDocument document;//= new XWPFDocument(POIXMLDocument.openPackage(srcPath));
document = new XWPFDocument(inputStream);
//1. 替换段落中的指定文字
Iterator itPara = document.getParagraphsIterator();
String text;
Set set;
XWPFParagraph paragraph;
List run;
String key;
while (itPara.hasNext()) {
paragraph = itPara.next();
set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
key = iterator.next();
run = paragraph.getRuns();
for (int i = 0, runSie = run.size(); i < runSie; i++) {
text = run.get(i).getText(run.get(i).getTextPosition());
if (text != null && text.equals(key)) {
run.get(i).setText(map.get(key), 0);
}
}
}
}
//2. 替换表格中的指定文字
Iterator itTable = document.getTablesIterator();
XWPFTable table;
int rowsCount;
while (itTable.hasNext()) {
table = itTable.next();
rowsCount = table.getNumberOfRows();
for (int i = 0; i < rowsCount; i++) {
XWPFTableRow row = table.getRow(i);
List cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
for (Entry e : map.entrySet()) {
if (cell.getText().equals(e.getKey())) {
cell.removeParagraph(0);
cell.setText(e.getValue());
}
}
}
}
}
//3.输出流
document.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}