关于前端:纯前端导出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 });
      });
    },

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理