使用freeMarker生成简单的word文档

1.创建一个word模板文件,填入需要生成的信息,需要动态传入的数据用${变量名}替换,如图。


2.将文件另存为xml格式。

3. 打开保存的xml文档,格式化xml文档,并检查${变量名} 是否分开,如果分开请手动修正。

 

 4.将xml格式改为ftl格式。

5.编写代码

        1)新建一个maven工程,导入依赖。

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>

        2)新建一个WordUtil工具类

        省去import

public class WordUtil {

    /**
     * 使用FreeMarker自动生成Word文档
     * @param dataMap 生成Word文档所需要的数据
     * @param fileName 生成Word文档的全路径名称
     * @param templateName 模板文件
     * @param templatePath 模板路径
     * @throws Exception
     */
    public static void generateWord(Map<String, Object> dataMap, String fileName,String templateName,String templatePath) throws Exception {
        // 设置FreeMarker的版本和编码格式
        //Configuration configuration = new Configuration(new Version("2.3.28"));
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");

        // 设置FreeMarker生成Word文档所需要的模板的路径
        configuration.setDirectoryForTemplateLoading(new File(templatePath));
        // 设置FreeMarker生成Word文档所需要的模板
        Template t = configuration.getTemplate(templateName, "UTF-8");
        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "UTF-8"));
        //FreeMarker使用Word模板和数据生成Word文档
        t.process(dataMap, out);
        out.flush();
        out.close();
    }
}

       3)编写测试类

    @Test
    public void test02() throws IOException {
        String path="D:\\IDEA_code\\javaUtils\\src\\main\\resources\\";
        String fileName="D:\\logs\\测试.doc";
        String templateName="测试1.ftl";
        String templatePath="D:\\IDEA_code\\javaUtils\\src\\main\\resources\\";
        Map<String,Object> map=new HashMap<>();
        map.put("name","sdsd");
        map.put("age",12);
        map.put("city","北京");
        try {
            WordUtil.generateWord(map,fileName,templateName,templatePath);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常");
        }
        System.out.println("生成成功");
    }

5.最后生成文档

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值