freemarker实现word导出

运行环境windows10 + eclipse

1、制作模板

新建word文档:

freemarker实现word导出

保存为.xml:

freemarker实现word导出

Firstobject free XML editor工具打开:

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

freemarker实现word导出

保存F2修改后缀名为ftl:

freemarker实现word导出

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、测试

freemarker实现word导出

word内容为:

freemarker实现word导出

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

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