Java 使用 poi 导出word 无法替换变量

最近在做一个根据模板导出word文件的功能,大体思路是在模板内使用变量占位,然后通过程序找到占位的变量,然后替换并导出。

经过一顿操作后发现一个问题,发现模板内有的变量可以被替换,有的不可以,模板如下 :

生成的word :

${sumMoney} 这个变量没有被替换,代码部分加上 println。

//替换表格部分的代码
for (XWPFTableRow row : rows) {
    List<XWPFTableCell> cells = row.getTableCells();//在行元素中,获得表格的单元格
    for (XWPFTableCell cell : cells) {   //遍历单元格
        List<XWPFParagraph> paragraphs = cell.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            String parText = paragraph.getText();//段落文字
            System.out.println(parText);
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                Stri
### Java 和 Apache POI 实现 Word 导出功能 要通过 Java 和 Apache POI 库实现 Word 文档的导出功能,可以利用 `XWPFDocument` 类来创建和操作 `.docx` 文件。以下是详细的说明以及一个完整的代码示例。 #### 依赖项配置 为了使用 Apache POI 创建 Word 文档,需要引入以下 Maven 依赖项: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> ``` 此版本为最新稳定版之一,可根据实际需求调整版本号[^2]。 #### 基本流程概述 1. **初始化文档对象**:创建一个新的 `XWPFDocument` 对象作为 Word 文档的基础。 2. **添加段落和文本**:通过调用 `createParagraph()` 方法向文档中添加段落,并设置其样式或内容。 3. **保存文件**:将生成的内容写入到指定路径下的 `.docx` 文件中。 下面是一个具体的例子展示如何完成这些步骤: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import java.io.FileOutputStream; import java.io.IOException; public class ExportWordExample { public static void main(String[] args) throws IOException { // Step 1: Create a blank document. XWPFDocument document = new XWPFDocument(); try (FileOutputStream out = new FileOutputStream("example.docx")) { // Step 2: Add paragraphs to the document with some text content. String titleText = "This is an Example Title"; XWPFParagraph paragraphTitle = document.createParagraph(); paragraphTitle.setAlignment(XWPFParagraph.Alignment.CENTER); // Center align the title. // Set bold style for the title. var runForTitle = paragraphTitle.createRun(); runForTitle.setBold(true); runForTitle.setText(titleText); // Adding another normal paragraph below the title. String bodyContent = "Here comes your detailed description or any other information."; XWPFParagraph paragraphBody = document.createParagraph(); var runForBody = paragraphBody.createRun(); runForBody.setText(bodyContent); // Step 3: Write the output to file system and close resources properly afterward. document.write(out); } finally { if (document != null) { document.close(); // Ensure resource cleanup after usage ends here too! } } System.out.println("Exported successfully!"); } } ``` 以上程序展示了怎样构建基本结构并填充简单文字信息至最终输出的目标文件里去[^2]。 #### 替换占位符扩展应用 如果希望进一步增强灵活性,则可以通过预先定义模板的方式,在其中预留特定标记位置供后续动态替换之用。比如采用 `${placeholder}` 形式的变量名形式嵌套于原始模版之中;之后再遍历读取整个文档查找匹配模式予以更新替换成真实数据值即可达成目的[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值