关于这个问题也是刚好遇到,一通搜索也没有找到类似的或者是有效的方法。下面介绍一下。

首先apache poi的引入

        <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency> <!-- poi_tl 工具,仅支持docx且友好
开源,官方文档:http://deepoove.com/poi-tl/1.10.x/
-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>

上面的包都是一些基础的东西,然后需要注意的是版本问题。因为版本不一样可能导致的用法也不一样。 poi-tl 1.10.0 版本需要poi 4.1.2的版本来支持。这个官方的作者已经说了。

下面直接上 替换word的代码

     XWPFDocument document = new XWPFDocument(in);

        List<XWPFParagraph> paragraphs = document.getParagraphs();

        Map<String, String> replacements = new HashMap<>();
    //这里是找回替换的特殊字符,我是通过正则去找回的。因为我的比较多。而且我一般习惯${}的写法。
    //当然poi-tl也可以直接替换很方便,但是这里用的是原生的apache poi。因为担心poi-tl还不是很成熟。
List<String> replaceFields = retrieveReplaceFields(document, regex);
for (String replaceField : replaceFields) {
String factField = StringUtils.substringBetween(replaceField, prefix, suffix);
String val = retrieveData(factField, data);
replacements.put(replaceField,val);
}
    //这里是普通段落
replaceInParagraphs(replacements,paragraphs); //处理表格
Iterator<XWPFTable> iterator = document.getTablesIterator();
while (iterator.hasNext()) {
XWPFTable table = iterator.next();
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> tableCells = row.getTableCells();
for (XWPFTableCell cell : tableCells) {
List<XWPFParagraph> cellParagraphs = cell.getParagraphs();
replaceInParagraphs(replacements,cellParagraphs);
}
}
} ByteArrayOutputStream output = new ByteArrayOutputStream(); document.write(output);
document.write(new FileOutputStream("C:\\Users\\dato\\Desktop\\dato.docx"));

这其中最重要替换方法来了:

replaceInParagraphs(replacements,cellParagraphs);

private static long replaceInParagraphs(Map<String, String> replacements, List<XWPFParagraph> xwpfParagraphs) {
long count = 0;
for (XWPFParagraph paragraph : xwpfParagraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (Map.Entry<String, String> replPair : replacements.entrySet()) {
String find = replPair.getKey();
String repl = replPair.getValue();
TextSegment found = paragraph.searchText(find, new PositionInParagraph());
if ( found != null ) {
count++;
if ( found.getBeginRun() == found.getEndRun() ) {
// whole search string is in one Run
XWPFRun run = runs.get(found.getBeginRun());
String runText = run.getText(run.getTextPosition());
String replaced = runText.replace(find, repl);
run.setText(replaced, 0);
} else {
// The search string spans over more than one Run
// Put the Strings together
StringBuilder b = new StringBuilder();
for (int runPos = found.getBeginRun(); runPos <= found.getEndRun(); runPos++) {
XWPFRun run = runs.get(runPos);
b.append(run.getText(run.getTextPosition()));
}
String connectedRuns = b.toString();
String replaced = connectedRuns.replace(find, repl);
// The first Run receives the replaced String of all connected Runs
XWPFRun partOne = runs.get(found.getBeginRun());
partOne.setText(replaced, 0);
// Removing the text in the other Runs.
for (int runPos = found.getBeginRun()+1; runPos <= found.getEndRun(); runPos++) {
XWPFRun partNext = runs.get(runPos);
partNext.setText("", 0);
}
}
}
}
}
return count;
}
 

最新文章

  1. CORS基础要点:关于dataType、contentType、withCredentials
  2. Hive UDF初探
  3. curl_init函数用法
  4. 怎么使用jquery判断一个元素是否含有一个指定的类(class)
  5. 利用KeyVault来加强存储Azure Storage访问密钥管理
  6. asp.net中三层架构与mvc之区别?
  7. .NET基础之集合
  8. JavaScript NodeList和Array
  9. Mac Mysql5.7.11安装和卸载
  10. Robot Framework与Web界面自动化测试学习笔记:简单例子
  11. 微信电脑版(Mac和Windows)安装
  12. Slow HTTP Denial of Service Attack 漏洞解决
  13. JavaScript之优化DOM
  14. 翻译:insert on duplicate key update(已提交到MariaDB官方手册)
  15. lsb_release command not found
  16. php之快速入门学习-7(运算符)
  17. 我是大SB
  18. sqlmap的简要使用方法
  19. 【ARC077F】SS kmp+打表找规律
  20. Spring Freamwork 开发初体验

热门文章

  1. python---括号匹配
  2. Mybatis-Dao层实现(通过代理方式)
  3. spring-基于注解的aop开发(快速入门)
  4. mysql-cluster-gpl-7.5.10-linux-glibc2.12-x86_64.tar.gz (有必要解释一下)
  5. springboot中bean的重定义
  6. MySQL启动过程详解三:Innodb存储引擎的启动
  7. 网页跟随系统 dark mode (暗黑模式) 的实现
  8. 读完学会shell语法,shell脚本80%已经学会
  9. 如何在Web前端实现CAD图文字全文搜索功能之技术分享
  10. 【题解】金牌导航-高斯消元/Luogu P3232 游走