JS 文件流方式下载Excel 问题

ajax请求中需要添加responseType 类型为blob
例如: xhr.responseType = 'blob'

1、未指定responseType

 

 
JS 文件流方式下载Excel 问题_xml
未指定


2、指定responseType

 
JS 文件流方式下载Excel 问题_ajax_02
指定

 

Vue中如下

export const getExcel = (params) => request({
  url: '/api/file',
  responseType: 'blob',
  method: 'get',
  params
})

下载

/**
 * Download file
 * @param {Bolb} b
 */
export const download = (content, filename = 'name') => {
  const a = document.createElement('a')
  // { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }
  
  // xls类型: application/vnd.ms-excel
  // xlsx类型:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
  const href = URL.createObjectURL(new Blob([content], { type: 'application/vnd.ms-excel' }))
  a.download = `${filename}.xls`
  a.href = href
  a.click()
  URL.revokeObjectURL(href)
}