freemarker导出word文档

本文介绍如何使用Freemarker将XML模板转换为Word文档,并详细解释了每个步骤的作用,包括创建模板、填充数据、保存文件等。
1、word建好模板,需要填值的地方先写上标记词

 

2、另存为.xml文件格式的文件

3、用编辑需要填值的关键词${xxx}替换,然后保存为.ftl文件。

4、新建一个map,key就是上面${}里面的字段。value就是需要填入word里的值

5、用freemarker中的Templeta类导入ftl模板并写入值


 
/**
     * 输出到输出到文件
     * @param ftlName   ftl文件名
     * @param root		传入的map
     * @param outFile	输出后的文件全部路径
     * @param ftlPath	模板的路径         
     */
    private static void printFile(String ftlName, Map<String,Object> root, String outFile, String ftlPath) throws Exception{
        Writer out = null;
        try {
            File file = new File(outFile);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            Template template = getTemplate(ftlName, ftlPath);
            template.process(root, out);					//模版输出
            out.flush();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
/**
     * 通过文件名加载模版
     * @param ftlName
     */
    public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
        try {
            Configuration cfg = new Configuration();  												//通过Freemaker的Configuration读取相应的ftl
            cfg.setEncoding(Locale.CHINA, "utf-8");
            cfg.setDirectoryForTemplateLoading(new File(ftlPath));				//设定去哪里读取相应的ftl模板文件
            Template temp = cfg.getTemplate(ftlName);												//在模板文件目录中找到名称为name的文件
            return temp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

ps:如有问题欢迎指出!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值