Apache Poi 操作word,替换字符保留样式问题,runs段落混乱问题。
2023-06-13 09:11:39 时间
关于这个问题也是刚好遇到,一通搜索也没有找到类似的或者是有效的方法。下面介绍一下。
首先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);
相关文章
- 百万级 Topic,Apache Pulsar 在腾讯云的稳定性优化实践
- 【漏洞复现】Apache HTTP Server 2.4.49、2.4.50 RCE(CVE-2021-41773)
- Apache Flink 1.16 功能解读
- 如何使用 Apache IoTDB 中的 UDF
- Linux下启动Apache服务的方法(linux启动apache)
- 搭配Apache MySQL:超强联手服务器助力(apache和mysql)
- 的结合Apache和MySQL的完美结合(apache与mysql)
- Apache Hadoop 2.6.0 新特性
- 使用Apache和MSSQL构建强大的数据库系统(apache mssql)
- 以Apache、MySQL和PHP组成的最强技术栈(apache mysql php)
- Linux下重启Apache简易指令.(linux重启apache命令)
- WINXP下apache+php4+mysql
- Apache配置伪静态详细步骤
- Apache配置详解(最好的APACHE配置教程)
- ubuntulamp(apache+mysql+php)环境搭建及相关扩展更新
- Windows下PHP安装路径配置错误导致Apache无法启动的解决方法