Java根据模板自动生成word————FreeMaker

根据模板自动生成word文件

介绍:

有一个很简易的工具能够替换word模板中的一些文字,生成新文件。

这个工具就是freemaker,先百度一下下个jar包。

具体使用:

  1. 要替换的部分用${}包裹起来;

  2. 将word文件另存为xml;

  3. 将此xml文件的后缀名改为ftl;

  4. 具体替换代码如下:

    package com.test;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    import java.io.Writer;
    import java.util.HashMap;
    import java.util.Map;
    
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    
    public class Test {
    	public static void main(String[] args) {
    		// 需要一个map来存放替换模板的值
    		Map<String, Object> dataMap = new HashMap<String, Object>();
    		// map的键名与模板中的一一对应
    		dataMap.put("title", "这是一个自动生成的标题");
    		Configuration configuration = new Configuration();
    		configuration.setDefaultEncoding("utf-8");
    
    		Writer out = null;
    		Template template = null;
    		try {
    			// 新建文件
    			File outFile = new File("C:\\Users\\15872\\Desktop\\test.doc");
    			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
    			// 读取模板所在目录
    			configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\15872\\Desktop"));
    			// 读取模板
    			template = configuration.getTemplate("test.ftl", "utf-8");
    			// 替换
    			template.process(dataMap, out);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (TemplateException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				out.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    
    	}
    }
    
    

效果如下:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值