2017-05-31 90 views
1

我在使用javascript导出表格时遇到问题。后端是春天,我在控制器中的方法看起来像这样。从服务器中导出excel表格中的javascript

@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,但是有些字节没有任何意义。

任何建议有什么不对?

回答

0

的.xlsx有不同的MIME type

的.xlsx:应用/ 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); 
    } 
    } 
+0

没什么..不过同样的问题,同样的行为.. –

+0

也许尝试在'axios.post设置'config parameter property'responseType:'blob',而不是在回调中转换它。 – barbsan

+0

我已经完成了将响应类型放入发布请求。 'axios.post( 网址+ '报告', 查询, {头:{ “访问控制允许报头”: “*”, “X-XSRF-TOKEN”:这$ cookie.get ('XSRF-TOKEN') }, responseType:“arraybuffer”, } ).....' –