前端json数据导出excel表格

108 阅读1分钟

前言

最近公司做的项目里面,有一些简单的表格导出的需求,后端同事比较忙点,所以自己这边动手前端导出了, 下面是我的使用dome,给大家分享一下

使用xlsx导出

目前xlsx不能修改样式,其他的配置可以参考 npm地址

安装

npm install xlsx
import * as XLSX from 'xlsx导出';

 const handleDownload = () => {
    // 需要导出的数据
    const exportArr = [
      { name: '张三', num: '1' },
      { name: '李四', num: '2' },
      { name: '王五', num: '3' },
    ];

    // 自定义下载的header,注意是数组中的数组哦
    const Header = [['名称', '数量']];

    // 官方文档中的描述:converts an array of arrays of JS data to a worksheet.
    const headerWs = XLSX.utils.aoa_to_sheet(Header);
    const ws = XLSX.utils.sheet_add_json(headerWs, exportArr, {
      skipHeader: true,
      origin: 'A2', // 对应的excel表里的A,从第二行开始
    });

    /* 新建空workbook,然后加入worksheet */
    const wb = XLSX.utils.book_new();

    // 可以自定义下载之后的sheetname
    XLSX.utils.book_append_sheet(wb, ws, 'sheet1');

    /* 生成xlsx文件 */
    XLSX.writeFile(wb, '导出.xlsx');
  };

const App = () =>{
    return  <Button onClick={handleDownload}>导出</Button>
}

导出示例

image.png

使用js导出

js导出的方式可以修改样式

import {Button} from 'antd';

const downFile = (data: any, fileName: string) => {
  const blob = data instanceof Blob ? data : new Blob([data]);

  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    let link: any = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
    link = null;
  }
};

const App = () =>{
 const handleDownload = () => {
     const exportFileContent = document.getElementById('my-table-id')?.outerHTML;
    let blob = new Blob([exportFileContent], {
      type: 'text/plain;charset=utf-8',
    }); //解决中文乱码问题
    blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
    downFile(blob, 'table.xlsx');
  };
    return <>
    <table id="my-table-id">
        <thead>
          <tr>
            <th>名称</th>
            <th>编号</th>
            <th>编号2</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ color: '#f00' }}>11</td>
            <td>编号2编号2编号2编号2编号2编号2</td>
          </tr>
          <tr>
            <td>33</td>
            <td>44</td>
          </tr>
        </tbody>
      </table>
      <Button onClick={handleDownload}>导出</Button>
    </>
}

导出的示例

image.png