2017-05-31 88 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」, } ).....' –