java 根据word模板导出导出word文档

2021-07-26 00:00:00 文档 模板 导出

一:新建需要导出word的模板,替换其中需要替换的字段,如下
《java 根据word模板导出导出word文档》

二:在桌面另存为如下格式
《java 根据word模板导出导出word文档》
三:另存的文件复制为如下路径,并修改文件后缀为ftl
《java 根据word模板导出导出word文档》
四: java 代码如下

@RequestMapping(value = "/importTemplateRH", method = RequestMethod.POST)
public void generateWorkContactLetters(HttpServletResponse response,
                                       @RequestParam(value = "companyAndName") String companyAndName,
                                       @RequestParam(value = "work") String work) throws Exception {
    //获取当前的日期
    Date date = new Date();
    //设置要获取到什么样的时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //获取String类型的时间
    String createdate = sdf.format(date);
    /** 初始化配置文件 **/
    @SuppressWarnings("deprecation")
    Configuration configuration = new Configuration();
    configuration.setDefaultEncoding("utf-8");
    /** 加载模板 **/

    //这个方法在eclipse跑和打jar包部署都可以获取到模版
    configuration.setClassForTemplateLoading(this.getClass(), "/templates");
    Template template = configuration.getTemplate("work.ftl");
    //这里是我获取的业务对象
    Map<String, Object> dataMap = new HashMap<>();

    dataMap.put("work", work);
    dataMap.put("companyAndName",companyAndName);
    dataMap.put("date", createdate == null ? "-" : com.sjft.common.core.utils.DateUtils.dateForOther(DateUtils.parseDate(createdate)));
    //开始word导出:导出我没有写死导出到什么磁盘,是通过浏览器输出随意存放修改。
    ServletOutputStream out = null;
    FileInputStream fin = null;
    String fileName = "报告.doc";
    try {

        //utils里创建word的方法:后面会给出代码
        File wordFile = WordUtil.createDoc(dataMap, template);
        fin = new FileInputStream(wordFile);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/msword;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + 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);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (fin != null)
            fin.close();
        if (out != null)
            out.close();
    }
}

五:wordUtils代码如下
package com.sjft.patorl.propaganda.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 WordUtil {

//配置信息
public static Configuration configuration = null;  
//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置  
private static String templateFolder;
//模板文件,可以方便修改
private static String fileInName; 
public WordUtil() {  
    
}
public WordUtil(String fileInName){
	WordUtil.fileInName=fileInName;

// templateFolder = WordUtil.class.getClassLoader().getResource(“…/…/”)+“META-INF/libs”;
// templateFolder = templateFolder.replaceAll(“%20″, ” “);
configuration = new Configuration();
configuration.setDefaultEncoding(“utf-8”);
try {
// configuration.setDirectoryForTemplateLoading(new File(templateFolder.substring(5)));
configuration.setClassForTemplateLoading(this.getClass(), “com/sjft/dailywork/resources/templates”);
configuration.getTemplate(fileInName);
configuration.setClassicCompatible(true); //解决null空值的问题
} catch (IOException e) {
e.printStackTrace();
}
}

public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String fileName) throws IOException {  
    Template freemarkerTemplate = configuration.getTemplate(fileInName);  
    File file = null;  
    InputStream fin = null;  
    ServletOutputStream out = null;  
    try {  
        // 调用工具类的createDoc方法生成Word文档  
        file = createDoc(map,freemarkerTemplate);  
        fin = new FileInputStream(file);  
        response.setContentType("application/msword");  
        // 设置浏览器以下载的方式处理该文件名  
        fileName +=  ".doc";  
        response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));  
        response.setCharacterEncoding("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(); // 删除临时文件  
    }  
} 

public 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;  
}  
public static void main(String[] args) {
	String path = WordUtil.class.getClassLoader().getSystemResource("META-INF").getPath();
	System.out.println(path);
}

}

至此,java 导出word完成

    原文作者:繁花落锦年
    原文地址: https://blog.csdn.net/qq_45611413/article/details/121276694
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章