在javascript中从服务器导出Excel表格

我在JavaScript中导出表格有问题。 后端是spring,我在控制器中的方法是这样的。

@PostMapping(produces = "application/vnd.ms-excel") public void report(@RequestBody @Validated final ReportRequest reportRequest, final HttpServletResponse response, final Principal principal) { log.info("'{}' Requested report '{}'", principal.getName(), reportRequest); final List<Data> dataList = dataRepository.findAll( findByCriteria( reportRequest.getFilterDatas(), reportRequest.getId(), reportRequest.getStartDate(), reportRequest.getEndDate())); final SXSSFWorkbook workbook = excelService.generateExcelFromDraData(dataList, FILE_NAME); writeToOutputStream(response, workbook); } 

在前端我使用vue.js和axios为http客户端。 而导出方法是:

 axios.post( url+'report', query, {headers: { "Access-Control-Allow-Headers" : "*", "X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN') } } ) .then((response) => { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); var url = window.URL.createObjectURL(blob); a.href = url; a.download = 'report.xlsx'; a.click(); window.URL.revokeObjectURL(url); }, (error) => { } ) 

当我用邮差打“发送和下载”,我得到我想要的Excel。 但是,当我从客户端做到这一点,我在console.log中得到响应的字节,但我不能打开excel消息'excel无法打开文件,因为文件格式或文件扩展名无效…'。 如果我把report.xls的名字,我得到excel我可以打开,但有一些字节,什么都没有意义。

任何build议有什么不对?

.xlsx具有不同的MIMEtypes :

.xlsx: application / vnd.openxmlformats-officedocument.spreadsheetml.sheet

请注意,浏览器也以不同的方式处理文件下载。 我已经成功地使用下面的代码(你将不得不改变它在你的应用程序中使用):

 function successCallback (data) { //In my case data was already a Blob if (window.navigator.msSaveOrOpenBlob) { //for IE window.navigator.msSaveOrOpenBlob(data, 'file.xlsx'); } else { var a = document.createElement("a"); a.href = window.URL.createObjectURL(data.slice()); a.target = '_blank'; a.download = 'file.xlsx'; a.dataset.downloadurl = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', a.download, a.href].join(':'); //a.click() got cancelled in firefox var event = document.createEvent("MouseEvent"); event.initMouseEvent( "click", true /* bubble */, false /* cancelable */, window, null, 0, 0, 0, 0, /* coordinates */ false, false, false, false, /* modifier keys */ 0 /*left*/, null ); a.dispatchEvent(event); } } 
Interesting Posts