> 文档中心 > Springboot + vue 实现导出word

Springboot + vue 实现导出word


Springboot + vue 实现导出word

后端代码

  1. 使用word先创建好已知的模板
    在这里插入图片描述

  2. 使用word工具另存为.xml格式的文件
    在这里插入图片描述

  3. 使用freemarker ftl模板
    将修改后的xml文件复制到开发工具中,将文件后缀修改为ftl文件,并且将里面的动态值使用${}包裹例如:${zyjn}

  4. word工具类

/* Project Name:maventest* 

生成word工具类
@ClassName: WordUtil @author zyl* @version 1.0* @since* @see*/public class WordUtil { // 字符编码格式 private static String charsetCode = "utf-8"; private Configuration configuration = null; / * 模板文件存放的目录 */ private static final String baseDir = "E:\\oracle\\demo - pdf中文问题\\src\\main\\resources\\freemaker";// private static final String baseDir = "/home/ruoyi/flt"; /* * 模板文件名称 */ private static final String templateFile = "mobanjianli.ftl"; /* * word生成的输出目录 */ private static final String outputDir = "E:\\oracle\\"; public WordUtil(){configuration = new Configuration();configuration.setDefaultEncoding("UTF-8"); } /* * * Project Name: maventest *

转换成word
* @version v1.0 * @since */ public void createWord(HttpServletResponse resp, HttpServletRequest req) throws IOException, BadElementException {Map dataMap=new HashMap();//构造参数getData(dataMap);configuration.setClassForTemplateLoading(this.getClass(), "");//模板文件所在路径Template t=null;try { configuration.setDirectoryForTemplateLoading(new File(baseDir)); t = configuration.getTemplate(templateFile);} catch (IOException e) { e.printStackTrace();}String str = Math.random()*10000 + ".doc";File outFile = new File(outputDir+str); //导出文件Writer out = null;try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));} catch (FileNotFoundException e1) { e1.printStackTrace();}try { t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件 System.out.println("生成成功..."); System.out.println("生成文件全路径:" + outputDir+str); downloadFile(outputDir+str,str,resp,req); out.close();} catch (TemplateException e) { e.printStackTrace();} catch (IOException e) { e.printStackTrace();} } / * * Project Name: maventest *

初始化数据map
* @version v1.0 * @since * @param dataMap * 封装数据的map */ private void getData(Map dataMap) throws IOException, BadElementException {dataMap.put("name", "刘德华");dataMap.put("sex", "男");dataMap.put("nation", "汉族");dataMap.put("birthday", "1985-02-26");String img = null;InputStream in;byte[] picdata = null;List staffList = new ArrayList();String ain = Base64ZM.Image2Base64("https://sxs-1302265538.cos.ap-beijing.myqcloud.com/image/1624887443344.jpg");BASE64Encoder encoder = new BASE64Encoder();dataMap.put("image", ain);dataMap.put("politicalStatus", "党员");dataMap.put("jg", "双叶幼稚园");dataMap.put("height", "幼稚园");dataMap.put("weight", "玩泥沙");dataMap.put("sfyjszgz", "NASA");dataMap.put("sfybyy", "煮菜的");dataMap.put("school", "lc");dataMap.put("zy", "lc");dataMap.put("education", "18898416969");dataMap.put("zyjn", "lc");dataMap.put("xxjl", "lc");dataMap.put("cjyry", "lc");dataMap.put("xqah", "lc");dataMap.put("jxjy", "2019");dataMap.put("zwpj", "02"); } // / * 下载文件 * @param path 文件的位置 * @param fileName 自定义下载文件的名称 * @param resp http响应 * @param req http请求 */ public static void downloadFile(String path, String fileName, HttpServletResponse resp, HttpServletRequest req){System.out.println("开始下载到本地");try { File file = new File(path); / * 中文乱码解决 */ String type = req.getHeader("User-Agent").toLowerCase(); if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){ / * 谷歌或火狐 */ fileName = new String(fileName.getBytes(charsetCode), "iso8859-1"); }else{ / * IE */ fileName = URLEncoder.encode(fileName, charsetCode); } // 设置响应的头部信息 resp.setHeader("content-disposition", "attachment;filename=" + fileName); // 设置响应内容的类型 resp.setContentType(getFileContentType(fileName)+"; charset=" + charsetCode); // 设置响应内容的长度 resp.setContentLength((int) file.length()); // 输出 outStream(new FileInputStream(file), resp.getOutputStream());} catch (Exception e) { System.out.println("执行downloadFile发生了异常:" + e.getMessage());} } / * 文件的内容类型 */ private static String getFileContentType(String name){String result = "";String fileType = name.toLowerCase();if (fileType.endsWith(".png")) { result = "image/png";} else if (fileType.endsWith(".gif")) { result = "image/gif";} else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) { result = "image/jpeg";} else if(fileType.endsWith(".svg")){ result = "image/svg+xml";}else if (fileType.endsWith(".doc")) { result = "application/msword";} else if (fileType.endsWith(".xls")) { result = "application/x-excel";} else if (fileType.endsWith(".zip")) { result = "application/zip";} else if (fileType.endsWith(".pdf")) { result = "application/pdf";} else { result = "application/octet-stream";}return result; } / * 基础字节数组输出 */ private static void outStream(InputStream is, OutputStream os) {try { byte[] buffer = new byte[10240]; int length = -1; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); os.flush(); }} catch (Exception e) { System.out.println("执行 outStream 发生了异常:" + e.getMessage());} finally { try { os.close(); } catch (IOException e) { } try { is.close(); } catch (IOException e) { }} }}

  1. 如果没有涉及图片可以忽略此步骤(图片转码工具类)
package com.example.demo.controller;import org.apache.tomcat.util.codec.binary.Base64;import org.springframework.util.StringUtils;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;public class ImageUtil {    /     * 将图片内容转换成Base64编码的字符串     * @param imageFile 图片文件的全路径名称     * @return 转换成Base64编码的图片内容字符串     */    public static String getImageBase64String(String imageFile) { if (StringUtils.isEmpty(imageFile)) {     return ""; } File file = new File(imageFile); if (!file.exists()) {     return ""; } InputStream is = null; byte[] data = null; try {     is = new FileInputStream(file);     data = new byte[is.available()];     is.read(data);     is.close(); } catch (IOException e) {     e.printStackTrace(); } return Base64.encodeBase64String(data);    }}
  1. controller接口调用
    @RequestMapping(value = "/exportWord", method = {RequestMethod.POST, RequestMethod.GET},     produces = MediaType.MULTIPART_FORM_DATA_VALUE)    public void exportWord(HttpServletResponse resp, HttpServletRequest req) throws IOException, BadElementException { WordUtil wordUtil = new WordUtil(); wordUtil.createWord(resp,req); System.out.println("导出word模板成功");    }

后端代码到此结束!!!!!!!!!!!

前端代码

直接通过流下载就可以了

handleWordInfo(row) {    exportWord(row.idCard).then(response =>{      let data = new Blob([response], { type: 'application/msword,charset=utf-8' });      if (typeof window.chrome !== 'undefined') {undefined var link = document.createElement('a'); link.href = window.URL.createObjectURL(data); link.download = row.name + "简历"; link.click();      } else if (typeof window.navigator.msSaveBlob !== 'undefined') {undefine // IE var blob = new Blob([data], { type: 'application/force-download' }); window.navigator.msSaveBlob(blob, row.name + "简历");      } else {undefined // Firefox var file = new File([data], row.name + "简历", { type: 'application/force-download' }); window.open(URL.createObjectURL(file));      }    })    // this.downloadFile("");  },

最后效果
在这里插入图片描述