为了账号安全,请及时绑定邮箱和手机立即绑定

java导出word文档 案例

标签:
JQuery

进行Javaweb文件导出为Word文档,使用freemarker时需要导入freemarker.jar。需要建立一个新的Word模板,填写处用${内容那么}代替。详细见http://blog.csdn.net/zhanwentao2/article/details/7255432/。
Java代码:
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 WordTest {

 private Configuration configuration = null;  

    public WordTest(){  
        configuration = new Configuration();  
        configuration.setDefaultEncoding("UTF-8");  
    }  

    public static void main(String[] args) {  
        WordTest test = new WordTest();  
        test.createWord();  
    }  

    public void createWord(){  
        Map<String,Object> dataMap=new HashMap<String,Object>();  
        getData(dataMap);  
        configuration.setClassForTemplateLoading(this.getClass(), "/com");  //FTL文件所存在的位置  
        Template t=null;  
        try {  
            t = configuration.getTemplate("wordModel.ftl"); //文件名  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        File outFile = new File("O:/outFilessa"+Math.random()*10000+".doc");  
        Writer out = null;  
        try {  
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));  
        } catch (FileNotFoundException e1) {  
            e1.printStackTrace();  
        }  

        try {  
            t.process(dataMap, out);  
        } catch (TemplateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

    private void getData(Map<String, Object> dataMap) {  
        dataMap.put("title", "标题");  
        dataMap.put("year", "2012");  
        dataMap.put("month", "2");  
        dataMap.put("day", "13");  
        dataMap.put("auditor", "唐鑫");  
        dataMap.put("phone", "13020265912");  
        dataMap.put("weave", "占文涛");  

// dataMap.put("number", 1);
// dataMap.put("content", "内容"+2);

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();  
        for (int i = 0; i < 10; i++) {  
            Map<String,Object> map = new HashMap<String,Object>();  
            map.put("number", i);  
            map.put("content", "内容"+i);  
            list.add(map);  
        }  

        dataMap.put("list", list);  
    }

}

点击查看更多内容
4人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
2
获赞与收藏
68

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消