使用Java导出word文档

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36675996/article/details/79442404

技术:使用FreeMarker的模板技术
思路:
1.先创建一个word文档,按照需求在word中填好一个模板,然后把对应的数据换成变量 2. > : w o r d 2003 X M L ( . x m l ) 3. x m l , {},正确的是<w:t>${xxx}</w:t>
4.再次另存为–>文件后缀名为.ftl
5.将该文件放到项目中.
实现:
引入jar包,maven形式:

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.27-incubating</version>
</dependency>

在项目中新建一个包,放入生成的ftl文件
这里写图片描述

编写代码:
DocUtil.java 工具类

package com.patent.apply.examinee;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

public class DocUtil {

    private static Configuration configuration = null;
    private static Map<String,Template> allTemplate = null;

    static{
        configuration = new Configuration(Configuration.VERSION_2_3_0);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(DocUtil.class, "/com/patent/apply/templates/");//放入项目中的ftl格式文件的路径
        allTemplate = new HashMap<String,Template>();
        try{
            allTemplate.put("test", configuration.getTemplate("shencha.ftl"));//放入项目中的ftl格式文件的名称
        }catch(IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private DocUtil(){
    }

    public static File createDoc(Map<?,?> dataMap,String type) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException{
        String name = "temp"+(int)(Math.random()*100000)+".doc";
        File f = new File(name);
        Template t = allTemplate.get(type);
        try{
            //这个地方不能使用FileWriter因为需要指定编码类型否则声场的word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f),"utf-8");
            t.process(dataMap,w);
            w.close();
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return f;
    }
}

在controller中,点击导出后的执行代码

@RequestMapping("/retest/payVolunteerPrint/print.action") //前台路径映射
    public String downResumeDoc(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        Map<String, Object> map = new HashMap<String, Object>();
        // 给map填充数据,也就是给模板中的${}所匹配
        map.put("xm", "张三");
        map.put("ksbh","李四");
        map.put("bknf", "2018");

        // 提示:在调用工具类生成Word文档之前应当检查所有字段是否完整
        // 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错,这里暂时忽略这个步骤
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;

        try {
            // 调用工具类WordGenerator的createDoc方法生成Word文档
            file = DocUtil.createDoc(map, "test");
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            String filename="导出文件名称.doc";
            //使用该方法,导出文件名如果是汉字,显示不出来
            //response.addHeader("Content-Disposition", "attachment;filename="+filename);
            //使用该方法,解决不显示汉字问题
            response.setHeader("Content-Disposition", "filename=\""+ new String(filename.getBytes("gb18030"), "ISO8859-1") + "\"");
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];// 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fin != null)
                fin.close();
            if (out != null)
                out.close();
            if (file != null)
                file.delete(); // 删除临时文件
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36675996/article/details/79442404