前端小知识集锦

208 阅读1分钟

vue&react项目中生成下载excel文档


// 下载模块功能
/**
 * 
 * @param {源数据流} response 
 * @param {*自定义的文件名} fileName 
 * return boolean {是否有数据,不需要也可以没有返回值}
 */
const download = async function (response, fileName) {
  // 使用一个buffer数组来读取 Response流中的数据,并将bodyUsed状态改为已使用
  const file = await response.arrayBuffer();
  let blob = new Blob([file], { type: 'application/vnd.ms-excel;charset=utf-8' })
  if (!blob.size) {
    // 如果没数据,返回false
    return false;
  }
  const url = window.URL.createObjectURL(blob);
  const downloadElement = document.createElement('a');
  downloadElement.href = url;
  downloadElement.download = fileName || 'download.xls';
  downloadElement.target = '_blank';
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(url);
  // 如果有数据,返回true
  return true;
}