栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基于freemarker实现导出word保姆版

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基于freemarker实现导出word保姆版

依赖:
        
            org.freemarker
            freemarker
            2.3.30
        
工具类
package com.cbnb.eob.base.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

public class WordUtils {
    private static Configuration configuration = null;
    //这里注意的是模板要放在resources/templete文件夹下
    private static final String templateFolder = WordUtils.class.getClassLoader().getResource("").getPath()+"templete/";

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private WordUtils() {
        throw new AssertionError();
    }

    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response,String name, Map map) throws IOException {
        //模板名称
        Template freemarkerTemplate = configuration.getTemplate(name+".ftl");
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map,freemarkerTemplate);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = name+".doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = response.getOutputStream();
            byte[] buffer = new byte[1024];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
            out.flush();
        } finally {
            if(fin != null) {
                fin.close();
            }
            if(out != null) {
                out.close();
            }
            if(file != null) {
                file.delete(); // 删除临时文件
            }
        }
    }

    private static File createDoc(Map dataMap, Template template) {
        String name =  "test.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}
工具类使用
  //查询符合性审查信息
        List voList = queryComplianceInspectionByItemId(projectId);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取不用循环的数据
        Map dataMap = new HashMap<>();
        dataMap.put("projectNo", voList.get(0).getProjectNo());
        dataMap.put("projectName", voList.get(0).getProjectName());
        dataMap.put("kbDate",formatter.format(voList.get(0).getKbDate()));
        dataMap.put("address", voList.get(0).getAddress());

        //获取需要循环的数据
        List> mpList = new ArrayList<>();

        voList.forEach( eobSupplierFitVO-> {
            Map map = new HashMap<>();
            map.put("deptName", eobSupplierFitVO.getDeptName());
            map.put("fitExamination", "0".equals(eobSupplierFitVO.getFitExamination()) ? "符合" : "不符合");
            map.put("details", eobSupplierFitVO.getDetails());
            mpList.add(map);
        });
        dataMap.put("mpList",mpList);
        WordUtils.exportMillCertificateWord(request,response,"符合性审查表",dataMap);
导出模板制作

1、先word中将要填充的属性填写在对应的位置上

2、将word另存为xml格式的文件
3、使用Sublime Text 或者其他软件打开xml文件
4、将文件保存为UTF-8的格式
5、在文件中查找对应的字段,使用 包 裹 住 , 如 {}包裹住,如 包裹住,如{projectNo},全部替换完保存
6、将文件后缀名改为flt格式
7、将ftl文件复制到项目下resources/templete

在项目中打开ftl文件

1、将其格式化 ctrl+alt+l
2、找到需要循环的行,w:tr 为行,w:tc 为列,使用list标签包裹住

                        <#list mpList as mpList>
                        
                            
                                
                            
                            
                                
                                    
                                    
                                
                                
                                    
                                        
                                        
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                    
                                        
                                            
                                            
                                            
                                            
                                        
                                        ${mpList?index+1}
                                    
                                    
                                
                            
                            
                                
                                    
                                    
                                    
                                
                                
                                    
                                        
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                        <#if mpList.deptName??>${mpList.deptName}
                                    
                                    
                                
                            
                            
                                
                                    
                                    
                                
                                
                                    
                                        
                                        
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                        <#if mpList.fitExamination??>${mpList.fitExamination}
                                    
                                    
                                
                            
                            
                                
                                    
                                    
                                    
                                
                                
                                    
                                        
                                        
                                        
                                            
                                            
                                            
                                        
                                    
                                    
                                        
                                            
                                            
                                            
                                        
                                        <#if mpList.details??>${mpList.details}
                                    
                                
                            
                        
                        

3、字段使用 mpList.xxx填充

<#if mpList.deptName??>${mpList.deptName}

4、序号从1开始

${mpList?index+1}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/778689.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号