java 模版式的 word

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.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 CreateWordTest { 
    // 参考 https://blog.csdn.net/chimaocai1302/article/details/100856467
    
    private Configuration configuration = null;
     
    public CreateWordTest() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }
 
    /** * * @param dataMap 要填充的数据集合 * 
     * @param fileName 生成的word文档路劲与名称 * 
     * @throws UnsupportedEncodingException */
    public void createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {
        System.out.println(dataMap);
        //读取模板   // /sdst4/src/com/jz/dzst/mail/zs_f.ftl
        configuration.setClassForTemplateLoading(this.getClass(), "/com/jz/dzst/mail");
        Template t=null;
        try {
            t = configuration.getTemplate("zs_f.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        File outFile = new File(fileName);
        Writer out = null;
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(outFile);
            //注意对流的编码
            OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
            out = new BufferedWriter(oWriter); 
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
 
        try {
            t.process(dataMap, out);
            out.close();
            fos.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        CreateWordTest createWordTest =new CreateWordTest();
        // 太长 附件会变成  .bin 文件
        String file_name = "abc.doc";
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            createWordTest.createDoc(map, file_name);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
时刻告诉自己,自己是个菜鸡......
原文地址:https://www.cnblogs.com/mysterious-killer/p/14393546.html