使用Sheetjs 实现纯前端导入导出xlsx

导语

SheetJS是前端操作Excel以及类似的二维表的最佳选择之一,而js-xlsx是它的社区版本.
js-xlsx将注意力集中到了数据转换和导出上,所以它支持相当多种类的数据解析和导出.不仅仅局限于支持xlsx格式.

提要

  • 安装 xlsx (npm / yarn )
npm i xlsx -D
yarn add xlsx
  • 引入 xlsx
import XLSX from 'xlsx';

代码

  • 导入excel
<input type='file' accept='.xlsx, .xls' onChange={(e) => { ExcelUtil.importExcel(e) }} />
// 导入xlsx
function importExcel(file) {
  // 获取上传的文件对象
  const { files } = file.target;
  // 通过FileReader对象读取文件
  const fileReader = new FileReader();

  fileReader.onload = event => {
    try {
      const { result } = event.target;
      //以二进制流方式读取得到整份excel表格对象
      const workbook = XLSX.read(result, { type: 'binary' });
      let data = []; //存储获取到的数据
      // 遍历每张工作表进行读取(这里默认只读取第一张表)
      for (const sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          // 利用 sheet_to_json 方法将 excel 转成 json 数据
          data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          // break; // 如果只取第一张表,就取消注释这行
        }
      }
      console.log(data);
    } catch (e) {
      // 抛出文件类型错误不正确的相关提示
      console.log('文件类型不正确');
      return;
    }
  };
  // 以二进制方式打开文件
  fileReader.readAsBinaryString(files[0]);

};
  • 导出 excel
 const initColumn = [{
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    className: 'text-monospace',
  }, {
    title: '年级',
    dataIndex: 'grade',
    key: 'grade',
  }, {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
  }];


  let attendanceInfoList = [
    {
      name: "张三",
      grade: "2017级",
      department: "前端部门"

    },
    {
      name: "李四",
      grade: "2017级",
      department: "程序部门"

    }];

<button type="primary" onClick={() => { ExcelUtil.exportExcel(initColumn, attendanceInfoList, "人员名单.xlsx") }}>导出</button>
// 导出xlsx
function exportExcel(headers, data, fileName = '记录表.xlsx') {
  const _headers = headers
    .map((item, i) => Object.assign({}, { key: item.key, title: item.title, position: String.fromCharCode(65 + i) + 1 }))
    .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { key: next.key, v: next.title } }), {});

  const _data = data
    .map((item, i) => headers.map((key, j) => Object.assign({}, { content: item[key.key], position: String.fromCharCode(65 + j) + (i + 2) })))
    // 对刚才的结果进行降维处理(二维数组变成一维数组)
    .reduce((prev, next) => prev.concat(next))
    // 转换成 worksheet 需要的结构
    .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});

  // 合并 headers 和 data
  const output = Object.assign({}, _headers, _data);
  // 获取所有单元格的位置
  const outputPos = Object.keys(output);
  // 计算出范围 ,["A1",..., "H2"]
  const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;

  // 构建 workbook 对象
  const wb = {
    SheetNames: ['mySheet'],
    Sheets: {
      mySheet: Object.assign(
        {},
        output,
        {
          '!ref': ref,
          '!cols': [{ wpx: 45 }, { wpx: 100 }, { wpx: 200 }, { wpx: 80 }, { wpx: 150 }, { wpx: 100 }, { wpx: 300 }, { wpx: 300 }],
        },
      ),
    },
  };

  // 导出 Excel
  XLSX.writeFile(wb, fileName);
}

效果图

图1 是excel转json
图2 是下载excel

效果图1

效果图2

总结

以前下载excel 都是后端在处理,现在可以自己玩了,还是很开心的;

参考资料

[SheetJS] js-xlsx模块学习指南

github 地址

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容