乐趣区

关于前端:纯前端导出xlsx文件

1. 装置 xlsx 插件。

yarn add xlsx  

2.export.js 文件封装导出函数。

import XLSX from 'xlsx';
function workbook2blob (workbook) {
  // 生成 excel 的配置项
  const wopts = {
    // 要生成的文件类型
    bookType: 'xlsx',
    // 是否生成 Shared String Table,官网解释是,如果开启生成速度会降落,但在低版本 IOS 设施上有更好的兼容性
    bookSST: false,
    type: 'binary'
  };
  const wbout = XLSX.write(workbook, wopts);
  // 将字符串转 ArrayBuffer
  function s2ab (s) {var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
  const buf = s2ab(wbout);
  const blob = new Blob([buf], {type: 'application/octet-stream'});
  return blob;
}
// 将 blob 对象 创立 bloburl, 而后用 a 标签实现弹出下载框
function openDownloadDialog (blob, fileName) {if (typeof blob === 'object' && blob instanceof Blob) {blob = URL.createObjectURL(blob); // 创立 blob 地址
  }
  const aLink = document.createElement('a');
  aLink.href = blob;
  // HTML5 新增的属性,指定保留文件名,能够不要后缀,留神,有时候 file:/// 模式下不会失效
  aLink.download = fileName || '';
  let event;
  if (window.MouseEvent) event = new MouseEvent('click');
  //   挪动端
  else {event = document.createEvent('MouseEvents');
    event.initMouseEvent(
      'click',
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
  }
  aLink.dispatchEvent(event);
}
function exportExcel ({name, data}) {
  //   let name = 'www';
  //   const data = [
  //     {
  //       data: [//         { department: '行政部', count: 2},
  //         {department: '行政部', count: 2}
  //       ],
  //       sheetName: 'sss'
  //     },
  //     {
  //       data: [//         { name: '李四', do: '打印'},
  //         {name: '李四', do: '打印'}
  //       ],
  //       sheetName: 'sss2'
  //     }
  //   ];

  const wb = XLSX.utils.book_new();
  data.forEach(item => {const sheet = XLSX.utils.json_to_sheet(item.sheetData);
    // 设置列宽
    sheet['!cols'] = [{ wch: 10},
      {wch: 10},
      {wch: 10},
      {wch: 10},
      {wch: 10},
      {wch: 5},
      {wch: 5},
      {wch: 5},
      {wch: 10},
      {wch: 12},
      {wch: 50}
    ];
    XLSX.utils.book_append_sheet(wb, sheet, item.sheetName);
  });
  const workbookBlob = workbook2blob(wb);
  openDownloadDialog(workbookBlob, `${name}.xlsx`);
}
export default exportExcel;

3. 触发导出事件,传入参数。

 exportCheckList () {
      const arr = [{ sheetName: '地夜阑', sheetData: [] },
        {sheetName: '地夜阑 2', sheetData: [] }
      ];
      // 解决数据格式
      //const data = this.handleExportData(arr);
      const name = 'test';
      import('./export.js').then(res => {res.default({ data, name});
      });
    },
退出移动版