Java读取word模板,通过占位符替换模板内容

前言

 本文章是有一个word文档的模板,在这个模板中,把自己要的内容添加到指定位置。

思路

获取模板的所有内容(InputStream)

找到你要填充的地方

设置占位符

进行替换

下载替换好的word文档(OutputStream)

  • 准备模板

我先在resources中准备好几个模板

  • 在模板中添加占位符

  • 读取模板

 我的环境是dev环境,所以我在application[dev].properties配置了存储模板的文件路径

在你所在的类中添加这一段(读取你在配置文件中的模板存储路径)

写一个方法,读取文件

//形参templateFileName是你模板名字
//使用InputStream读取
private InputStream prepareFile(String templateFileName) throws IOException {
        return new FileInputStream(templateFilePath + "/" + templateFileName);
    }

把模板读取出来

//调用上面写的方法prepareFile把文件名传入
InputStream template = prepareFile("XXX.docx");
//创建XWPFDocument对象,表示Word文档
XWPFDocument document = new XWPFDocument(template);
  • 替换内容

//获取所有段落
List<XWPFParagraph> paragraphList = document.getParagraphs();
//遍历段落
for (int i = 0; i < paragraphList.size(); i++) {
    //获取每个段落
    XWPFParagraph paragraph = paragraphList.get(i);
    //获取每个段落中的内容
    List<XWPFRun> runs = paragraph.getRuns();
    //循环段落内容
    for (int i1 = 0; i1 < runs.size(); i1++) {
        //调用自定义方法replacePlaceholderV2替换内容
        if (runs.get(i1).toString().contains("name")) {
            replacePlaceholderV2(runs.get(i1), "name", infoPojo.getPatientName());
         }
}
}

自定义方法replacePlaceholderV2

 /**
     * @param run         文本内容
     * @param placeholder 模板中自定义的占位符
     * @param replacement 替换的内容
     * @throws IOException
     * @throws InvalidFormatException
     */
    private static void replacePlaceholderV2(XWPFRun run, String placeholder, String replacement) throws IOException, InvalidFormatException {
        // 获取当前XWPFRun对象的文本内容
        String text = run.getText(0);
        // 判断文本内容是否包含占位符
        if (text != null && text.contains(placeholder)) {
            // 替换文本中的占位符为指定的替换内容,并更新XWPFRun的文本内容
            run.setText(text.replace(placeholder, replacement.replace("[", "").replace("]", "")), 0);
        }
    }

 下载替换内容后的模板

// 将填充后的文档写入输出流
document.write(output);
// 关闭模板输入流和文档
template.close();
document.close();
  • 最终成果

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用POI库来实现在Java中根据Word模板生成Word文档。以下是基本的步骤: 1. 创建一个Word模板文件,将需要动态生成的变量用占位符(如${variable})替换。 2. 在Java中使用POI库打开模板文件,读取替换占位符。 3. 将替换后的内容写入到新的Word文档中。 4. 保存新的Word文档。 示例代码如下: ``` import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class WordTemplateGenerator { public static void main(String[] args) throws Exception { // 读取Word模板文件 FileInputStream fis = new FileInputStream(new File("template.docx")); XWPFDocument document = new XWPFDocument(fis); // 替换模板中的变量 Map<String, String> variables = new HashMap<>(); variables.put("name", "张三"); variables.put("age", "25"); variables.put("address", "北京市海淀区"); replaceVariables(document, variables); // 保存新的Word文档 FileOutputStream fos = new FileOutputStream(new File("output.docx")); document.write(fos); fos.close(); document.close(); } private static void replaceVariables(XWPFDocument document, Map<String, String> variables) { for (XWPFParagraph paragraph : document.getParagraphs()) { replaceInParagraph(paragraph, variables); } for (XWPFTable table : document.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph paragraph : cell.getParagraphs()) { replaceInParagraph(paragraph, variables); } } } } } private static void replaceInParagraph(XWPFParagraph paragraph, Map<String, String> variables) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (String variable : variables.keySet()) { if (text.contains(variable)) { text = text.replace(variable, variables.get(variable)); run.setText(text, 0); } } } } } } ``` 在上述示例代码中,我们使用了XWPFDocument类来读取Word模板文件和生成新的Word文档。replaceVariables()方法用于替换模板中的变量,replaceInParagraph()方法用于替换段落中的变量。在示例代码中,我们假设模板中的变量为name、age和address。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值