阅读 523

前端导出xlsx

前端导出xlsx工具函数

表格宽度自适应,多sheet

首先安装xlsx,参数看exportExcel的参数

import { WorkSheet } from 'xlsx';

function jsonToArray (key: string[], jsonData: object[]) {
  return jsonData.map((v: { [x: string]: any }) =>
    key.map((j: string | number) => {
      return v[j];
    })
  );
}

function autoWidthFunc (ws: WorkSheet, data: any[]) {
  // set worksheet max width per col
  const colWidth = data.map((row: any[]) =>
    row.map(val => {
      // if null/undefined
      if (val == null) {
        return { wch: 10 };
      } else if (val.toString().charCodeAt(0) > 255) {
        // if chinese
        return { wch: val.toString().length * 2 };
      } else {
        return { wch: val.toString().length };
      }
    })
  );
  // start in the first row
  const result = colWidth[0];
  for (let i = 1; i < colWidth.length; i++) {
    for (let j = 0; j < colWidth[i].length; j++) {
      if (result[j].wch < colWidth[i][j].wch) {
        result[j].wch = colWidth[i][j].wch;
      }
    }
  }
  ws['!cols'] = result;
}

type dataItem = {
  sheetData: [];
  sheetName: string;
};

const exportExcel = ({
  key,
  data,
  title,
  filename,
  autoWidth
}: {
  key: string[];
  data: dataItem[];
  title: string[];
  filename: string;
  autoWidth: boolean;
}) => {
  import('xlsx').then(XLSX => {
    const wb = XLSX.utils.book_new();
    data.forEach(item => {
      const arr = jsonToArray(key, item.sheetData);
      arr.unshift(title);
      const ws = XLSX.utils.aoa_to_sheet(arr);
      if (autoWidth) {
        autoWidthFunc(ws, arr);
      }
      XLSX.utils.book_append_sheet(wb, ws, item.sheetName);
    });
    XLSX.writeFile(wb, filename + '.xlsx');
  });
};

export default exportExcel;

复制代码
文章分类
前端
文章标签