java IO 基于模板文件替换字符生成word文档

有很多人会选择用POI来实现这个功能,虽然说POI第三方包提供了很多方法,但JAVA IO流也不是吃素的,同样也可以实现基于模板文件替换字符生成文档.
这个功能在web应用中还是蛮常见的,用户们喜欢根据自己的模板,然后在加上提供的内容,自动生成出不同的word文档,省时省力.现在直接贴出代码.

public class WangTest {
   
   

    public static void main(String[] args) {

        String templateContent = null;
        String filePath = "D:/newWorkSpace20160516/SCPT/WebRoot/template/wangtest.mht";//模版文件
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
        }
        BufferedInputStream in = 
### 使用 Java 和 POI 库基于模板替换字符串并导出 Word 文档 为了实现通过模板文件中的占位符进行字符替换并将结果保存为新的 Word 文件,可以利用 Apache POI 库。下面提供了一个具体的例子说明如何操作。 #### 导入依赖项 首先,在项目中引入必要的 Maven 依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> ``` #### 替换模板中的文本 创建一个名为 `TemplateProcessor` 的类用于处理文档内的文字替换工作: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.List; import java.util.Map; public class TemplateProcessor { public static void processTemplate(String inputPath, String outputPath, Map<String, String> replacements) throws Exception { try (FileInputStream fis = new FileInputStream(inputPath); XWPFDocument document = new XWPFDocument(fis)) { List<XWPFParagraph> paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { for (Map.Entry<String, String> entry : replacements.entrySet()) { if (paragraph.getText().contains(entry.getKey())) { paragraph.replaceText(entry.getKey(), entry.getValue()); } } } try (FileOutputStream fos = new FileOutputStream(outputPath)) { document.write(fos); } } } } ``` 这段代码遍历整个 `.docx` 文件里的每一个段落对象,并尝试匹配给定键值对中的关键字;一旦找到对应关系,则执行相应的替换动作[^1]。 #### 调用示例 假设有一个预先准备好的模板文件叫做 "template.docx" ,其中含有诸如 `${name}` 或者 `${date}` 形式的占位符等待被实际数据所取代。那么可以通过如下方式调用上述定义的方法完成最终的目标: ```java import java.util.HashMap; import java.util.Map; public class MainApp { public static void main(String[] args) throws Exception{ // 准备要填充的数据 Map<String, String> data = new HashMap<>(); data.put("${name}", "张三"); data.put("${date}", "2024年1月8日"); // 处理模板生成文件 TemplateProcessor.processTemplate( "./src/main/resources/template.docx", "./output/generated_document.docx", data); System.out.println("文档已成功生成!"); } } ``` 此程序片段展示了怎样设置待插入的具体内容以及指定输入输出路径来启动整个程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值