首页 > 编程语言 > 详细

java 模版式的 word

时间:2021-02-09 18:17:19      阅读:27      评论:0      收藏:0      [点我收藏+]
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();
        }
    }

}

 

java 模版式的 word

原文:https://www.cnblogs.com/mysterious-killer/p/14393546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!