Springboot + vue 实现导出word

Springboot + vue 实现导出word,第1张

Springboot + vue 实现导出word Springboot + vue 实现导出word 后端代码
  1. 使用word先创建好已知的模板

  2. 使用word工具另存为.xml格式的文件

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

  4. word工具类

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";
   
   private static final String  outputDir = "E:\oracle\";

   public WordUtil(){
       configuration = new Configuration();
       configuration.setDefaultEncoding("UTF-8");
   }

   
   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();
       }
   }

   
   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");

   }




   
   
   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{
               
               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 {
    
    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("");
  },

最后效果

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5611675.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存