开头贴出参考文章地址:
http://blog.sina.com.cn/s/blog_885585cb0101gnz7.html
http://www.cnblogs.com/dreammyle/p/5159267.html
效果图:原docx文件
效果图:替换后的docx文件
maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
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<String, String> 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<String, String> map) {
try {
XWPFDocument document;//= new XWPFDocument(POIXMLDocument.openPackage(srcPath));
document = new XWPFDocument(inputStream);
//1. 替换段落中的指定文字
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
String text;
Set<String> set;
XWPFParagraph paragraph;
List<XWPFRun> run;
String key;
while (itPara.hasNext()) {
paragraph = itPara.next();
set = map.keySet();
Iterator<String> 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<XWPFTable> 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<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
for (Entry<String, String> 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();
}
}
}