springboot+vue+element-ui下载excel模板(静态文件)
生活随笔
收集整理的這篇文章主要介紹了
springboot+vue+element-ui下载excel模板(静态文件)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前端:?
html:<div style="margin-top: 20px"><el-button @click="downloadDemo" size="small">下載模板</el-button></div>js:downloadDemo () {let url = Config.context + '/userManager/downloadExcel'this.common.exportData(url, this.queryForm, '數(shù)據(jù)模板_' + 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 = uaLink.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<byte[]> 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;@Service public class ExcelModelService {public File buildXlsById(){//do something to find this fileFile file=null;try {file = ResourceUtils.getFile("classpath:templates/model.xlsx");} catch (FileNotFoundException e) {e.printStackTrace();}return file;} }這里寫的是靜態(tài)文件的存放路徑,注意不能中文名不然識(shí)別不了
文件下載工具類:
public static ResponseEntity<byte[]> 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();//設(shè)置文件類型headers.add("Content-Disposition", "attchement;filename=" + file.getName());//設(shè)置Http狀態(tài)碼HttpStatus statusCode = HttpStatus.OK;//返回?cái)?shù)據(jù)ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);return entity;}后續(xù)補(bǔ)充:
? 以上方式實(shí)現(xiàn)在開發(fā)環(huán)境沒(méi)有任何問(wèn)題,但是在生產(chǎn)環(huán)境會(huì)出現(xiàn)無(wú)法下載后臺(tái)報(bào)錯(cuò)的情況,原因在于用流的方式讀取文件,打成jar包之后,下載的文件會(huì)被損壞?,后來(lái)網(wǎng)上說(shuō)配置pom里面文件路徑等等試了沒(méi)用,直接用了POI的導(dǎo)出
修改后controller:
@RequestMapping(value="/downloadExcel")public ResponseEntity<Resource> 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return new ResponseEntity<Resource>(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();}}?
總結(jié)
以上是生活随笔為你收集整理的springboot+vue+element-ui下载excel模板(静态文件)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: HTML5的骨架
- 下一篇: Prometheus 容器化部署,配合G