java web 使用 Freemarker 导出word,zip包导出多个word

       曾经使用POI做过导出excel的功能,有次客户需要做导出word。使用过POI 导出excel都知道,
POI可以根据每行row提供第n个单元格cell操作的。但word 又不像excel 那样一格一格的那么整齐,
想把数据填到特定的地方还比较麻烦,所以,想到了Freemarker。

1.制作word的ftl模板
      将word要填充数据的地方用***代替,然后另存为Word 2003 XML 文档(*.xml),保存的文件名不要是中文。

2.用Firstobject free XML editor打开xml文件,先格式化文件内容:选择Tools下的Indent【或者按快捷键F8】,
然后逐个ctrl+f 查找***,用freemarker的标识替换掉***,如:${name},这个name对应的是填充数据Map对应的key。
然后另存为.ftl文件,模板就做好啦!

3.代码实现:
导出word工具类:WordUtils

public class WordUtils {
      
    private static Configuration configuration = null;  
    
    static {  
        configuration = new Configuration();  
        configuration.setDefaultEncoding("utf-8");  
        try {  
        	ResourceLoader resourceLoader = new DefaultResourceLoader();
            //指定模板目录在类路径:WEB-INF/classes
			Resource resource = resourceLoader.getResource("/");
			File file = resource.getFile();
			//设置要解析的模板所在的目录,并加载模板文件
			configuration.setDirectoryForTemplateLoading(file);
            ///设置包装器,并将对象包装为数据模型
			configuration.setObjectWrapper(new DefaultObjectWrapper());
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
   }  
  
    private WordUtils() {  
        throw new AssertionError();  
    }  
  
    /*
    *导出单个word
    *map:数据
    *title:文件名
    *ftlFile:模板文件
    */
    public static void exportWord(Map map,String title,String ftlFile) {  
        
        File file = null;  
        InputStream fin = null;  
        ServletOutputStream out = null;
        HttpServletRequest request=WebUtils.getRequest();
		HttpServletResponse response=WebUtils.getResponse();
        try {  
        	Template freemarkerTemplate = configuration.getTemplate(ftlFile,"UTF-8"); 
            // 调用工具类的createDoc方法生成Word文档
        	String fileName = title+ ".doc";  
            file = createDoc(map,freemarkerTemplate,fileName);  
            fin = new FileInputStream(file);  
  
            response.setCharacterEncoding("utf-8");  
            response.setContentType("application/msword");  
            // 设置浏览器以下载的方式处理该文件名  
            
            response.setHeader("Content-Disposition", "attachment;filename="  
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));  
  
            out = response.getOutputStream();  
            byte[] buffer = new byte[512];  // 缓冲区  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值