博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot+vue+element-ui下载excel模板(静态文件)
阅读量:3910 次
发布时间:2019-05-23

本文共 3806 字,大约阅读时间需要 12 分钟。

前端: 

html:      
下载模板
js: downloadDemo () { let url = Config.context + '/userManager/downloadExcel' this.common.exportData(url, this.queryForm, '数据模板_' + this.common.getTime()) }
exportData (url, data, fileName) {    axios({      method: 'POST',      url: url,      data: data,      responseType: 'blob'    }).then(response => {      if (!response) {        return      }      const blob = new Blob([response.data])      if (window.navigator && window.navigator.msSaveOrOpenBlob) {        navigator.msSaveBlob(blob, fileName)      } else {        let u = window.URL.createObjectURL(response.data)        let aLink = document.createElement('a')        aLink.style.display = 'none'        aLink.href = u        aLink.setAttribute('download', fileName + '.xlsx')        document.body.appendChild(aLink)        aLink.click()        document.body.removeChild(aLink)        window.URL.revokeObjectURL(u)      }    }).catch(error => {      throw error    })  }

 

后端:

controller层:

@RequestMapping("/downloadExcel")    public ResponseEntity
download2() throws IOException { File file = excelModelService.buildXlsById(); return FileUtils.buildResponseEntity(file); }

service层:

import org.springframework.stereotype.Service;import org.springframework.util.ResourceUtils;import java.io.File;import java.io.FileNotFoundException;@Servicepublic class ExcelModelService {    public File buildXlsById(){        //do something to find this file        File file=null;        try {            file = ResourceUtils.getFile("classpath:templates/model.xlsx");        } catch (FileNotFoundException e) {            e.printStackTrace();        }        return file;    }}

这里写的是静态文件的存放路径,注意不能中文名不然识别不了

文件下载工具类:

public static ResponseEntity
buildResponseEntity(File file) throws IOException { byte[] body = null; //获取文件 InputStream is = new FileInputStream(file); body = new byte[is.available()]; is.read(body); HttpHeaders headers = new HttpHeaders(); //设置文件类型 headers.add("Content-Disposition", "attchement;filename=" + file.getName()); //设置Http状态码 HttpStatus statusCode = HttpStatus.OK; //返回数据 ResponseEntity
entity = new ResponseEntity
(body, headers, statusCode); return entity; }

后续补充:

  以上方式实现在开发环境没有任何问题,但是在生产环境会出现无法下载后台报错的情况,原因在于用流的方式读取文件,打成jar包之后,下载的文件会被损坏 ,后来网上说配置pom里面文件路径等等试了没用,直接用了POI的导出

修改后controller:

@RequestMapping(value="/downloadExcel")    public ResponseEntity
excel2007Export(HttpServletResponse response, HttpServletRequest request) { try { ClassPathResource cpr = new ClassPathResource("/templates/"+"model.xlsx"); InputStream is = cpr.getInputStream(); Workbook workbook = new XSSFWorkbook(is); String fileName = "model.xlsx"; downLoadExcel(fileName, response, workbook); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new ResponseEntity
(HttpStatus.OK); }

文件工具类downLoadExcel:

public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {        try {            response.setCharacterEncoding("UTF-8");            response.setHeader("content-Type", "application/vnd.ms-excel");            response.setHeader("Content-Disposition",                    "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");            workbook.write(response.getOutputStream());        } catch (IOException e) {            e.printStackTrace();        }    }

 

转载地址:http://aawrn.baihongyu.com/

你可能感兴趣的文章
java面向对象设计的六大原则
查看>>
java面向对象6大原则2
查看>>
java线程池学习
查看>>
Java线程:概念与原理
查看>>
Java线程:并发协作-死锁
查看>>
《构建高性能web站点》笔记--基础架构篇
查看>>
以太坊源码分析---go-ethereum之p2p通信分析(1)
查看>>
以太坊源码分析---go-ethereum之p2p通信分析(2)
查看>>
groupcache源码分析
查看>>
go-metrics源码分析
查看>>
beego/cache源码分析---典型的工厂模式
查看>>
Boltdb源码分析(一)-------page结构
查看>>
Boltdb源码分析(二)----node结构
查看>>
Go标准库plugin源码分析----动态库使用
查看>>
开源代码学习-nsq(v0.1.1版本)源码分析
查看>>
开源代码学习-nsq(v0.1.5版本)源码分析
查看>>
开源代码protoactor-go[e866f39]源码分析
查看>>
开源代码protoactor-go源码分析-async schedule
查看>>
开源代码TarsGo-v1.0.0源码分析之transport
查看>>
本人公众号技术文章目录-持续更新
查看>>