前端导出excel

165 阅读1分钟

前端将后端api返回的流文件转成excel:

    downloadExcel(res){
      const file = res.headers["content-disposition"].split(";")[1];
      const fileName = decodeURI(file.split("=")[1]);
      let a = document.createElement("a");
      let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
      let objectUrl = URL.createObjectURL(blob);
      a.setAttribute("href", objectUrl);
      a.setAttribute("download", fileName);
      a.click();
    },

调用后端api的responseType: "arraybuffer",这个解决文件打开乱码问题,以aixos为例:

export function exportMergeConflicts(params) {
  return request({
    url: '/cms/mergeConflict/exportMergeConflicts',
    responseType: "arraybuffer",
    method: 'post',
    data: params
  })
}
exportMergeConflicts(params).then(res => {
    this.downloadExcel(res)
})