freemarker实现word导出

运行环境windows10 + eclipse

1、制作模板

新建word文档:

保存为.xml:

Firstobject free XML editor工具打开:

Firstobject free XML editor下载地址:http://www.firstobject.com/dn_editor.htm

保存F2修改后缀名为ftl:

2、编写测试类

package com.ultrapower.eoms.ultrabpp.runtime.extend.UBP_MSCC_CHANGE;
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.Writer;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  
import freemarker.template.Configuration;  
import freemarker.template.Template;  
import freemarker.template.TemplateException;  
public class ExportWord {
    private Configuration configuration = null;  
    
    public ExportWord(){  
        configuration = new Configuration();  
        configuration.setDefaultEncoding("UTF-8");  
    }  
      
    public static void main(String[] args) {  
        ExportWord test = new ExportWord();  
        test.createWord();  
    }  
      
    public void createWord(){  
        try {
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("username", "张三");
            dataMap.put("pwd", "男");
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\Mrzhao\\Desktop"));
            // 输出文档路径及名称  
            File outFile = new File("D:/test.doc");
            //以utf-8的编码读取ftl文件  
            Template t = configuration.getTemplate("test.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            t.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            // TODO: handle exception
        } 
    }  
  
    
}
 

3、测试

word内容为:

被成功替换,至此,最基本的word导出完成。

详情请参考:freemarker 官网:http://freemarker.org/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值