java ~ word模板填充字符后输出到指定目录

本文介绍了如何在Java项目中通过POI-TL库处理Word文档,包括添加依赖、封装数据和编写样例代码,展示了如何将数据渲染到Word模板并保存为新文件。
摘要由CSDN通过智能技术生成

word文件格式:

替换字符串date为指定日期

jar包:

	<dependency>
		<groupId>com.deepoove</groupId>
		<artifactId>poi-tl</artifactId>
		<version>1.10.0</version>
	</dependency>

样例代码:

	// 封装参数集合
	Map<String, Object> data = new HashMap<String, Object>() {{
         put("date", DateUtil.format("yyyy年MM月dd日", new Date()));
     }};

	try (InputStream is = new ClassPathResource("file/path/fileName.docx").getInputStream()) {
	ConfigureBuilder builder = Configure.builder();
	    XWPFTemplate template = XWPFTemplate.compile(is, builder.build()).render(data);
	    String wordPath = "E:\\newFileName.docx";
	    template.writeAndClose(Files.newOutputStream(Paths.get(wordPath)));
	} catch (IOException e) {
	    throw new RuntimeException(e);
	}
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用Apache POI和Freemarker两个库来实现根据模板导出数据到word的解决方案。 Apache POI是一个Java API,可以用于读写Microsoft Office格式的文档,包括Word、Excel和PowerPoint等。使用Apache POI,可以在Java程序中创建、修改和读取Word文档,将数据填充Word文档中的模板中,生成新的Word文档。 Freemarker是一个模板引擎,可以将数据填充模板中,生成新的文本文件,包括HTML、XML、JSON和Word等。使用Freemarker,可以将数据填充Word文档中的模板中,生成新的Word文档。 具体实现步骤如下: 1. 创建Word文档模板,使用Word软件设计好需要填充数据的文档模板。 2. 使用Apache POI读取Word文档模板,获取到需要填充数据的位置和格式。 3. 使用Freemarker将数据填充Word文档模板中,生成新的Word文档。 4. 将生成的新的Word文档保存到文件或输出到浏览器。 这是一个基本的实现流程,具体实现细节可以参考相关的文档和示例代码。以下是一个基本的示例代码: ``` // 1. 创建Word文档模板 FileInputStream fis = new FileInputStream("template.docx"); XWPFDocument templateDoc = new XWPFDocument(fis); fis.close(); // 2. 使用Apache POI读取Word文档模板 for (XWPFParagraph paragraph : templateDoc.getParagraphs()) { List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if (text != null && text.contains("${")) { // 找到需要填充位置 // 可以使用正则表达式或者字符串替换等方式进行定位 } } } // 3. 使用Freemarker将数据填充Word文档模板中 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(this.getClass(), "/templates"); Template template = cfg.getTemplate("template.ftl"); Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 20); StringWriter sw = new StringWriter(); template.process(data, sw); String content = sw.toString(); // 4. 将生成的新的Word文档保存到文件或输出到浏览器 XWPFDocument newDoc = new XWPFDocument(); XWPFParagraph newParagraph = newDoc.createParagraph(); XWPFRun newRun = newParagraph.createRun(); newRun.setText(content); FileOutputStream fos = new FileOutputStream("output.docx"); newDoc.write(fos); fos.close(); newDoc.close(); ``` 上述代码使用了一个模板文件`template.ftl`,该文件中包含了需要填充的数据的位置和格式。在代码中,使用Freemarker将数据填充模板中,生成新的内容`content`,然后将新的内容生成为一个新的Word文档并保存到文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值