xlsxjs 导出excel文件 简易上手

博客介绍了 xlsx 插件的相关操作,包括安装该插件,提取其导出方法,以及如何使用该插件,为信息技术领域中涉及插件使用的操作提供了指引。
1、安装 xlsx 插件
yarn add xlsx
2、导出方法提取
import * as XLSX from 'xlsx/xlsx.mjs';
/**
 * 导出excel
 * @param {*} headers 表头
 * @param {*} data 表格数据
 * @param {*} fileName 导出文件名
 */
const exportExcel = (headers: any, data: any, fileName = 'demo.xlsx') => {
  const _headers = headers
    .map((item: any, i: number) =>
      Object.assign(
        {},
        {
          key: item.key,
          title: item.title,
          position: String.fromCharCode(65 + i) + 1,
        },
      ),
    )
    .reduce(
      (prev: any, next: any) =>
        Object.assign({}, prev, {
          [next.position]: { key: next.key, v: next.title },
        }),
      {},
    );
  const _data =
    (data.length > 0 &&
      data
        .map((item: any, i: number) =>
          headers.map((key: any, j: number) =>
            Object.assign(
              {},
              {
                content: item[key.key],
                position: String.fromCharCode(65 + j) + (i + 2),
              },
            ),
          ),
        )
        // 对刚才的结果进行降维处理(二维数组变成一维数组)
        .reduce((prev: any, next: any) => prev.concat(next))
        // 转换成 worksheet 需要的结构
        .reduce((prev: any, next: any) => 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 },
        ],
      }),
    },
  };
  console.log('%c 下载文件===========> ', 'background: #222; color: #bada55', wb, fileName);
  // 导出 Excel
  return XLSX.writeFile(wb, fileName);
};
3、使用
const exportFile = async () => {
    let header = [
      {
        title: '姓名',
        key: 'name',
      },
      {
        title: '年龄',
        key: 'age',
      },
    ];
    return exportExcel(header, [], `output.xlsx`);
  };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值