干货|基于React和xlsx库导出表格数据到excel(前端操作)

注:要根据 columnsdataSource 来导出数据,导出的内容应该包括 columns 作为表头,以及每一行的数据。编写 exportToExcel 函数,将 columnsdataSource 结合起来进行导出。

实例:

javascript 复制代码
import React from 'react';
import { Button, Table } from 'antd';
import * as XLSX from 'xlsx';

const TestComponent: React.FC = () => {
  const dataSource = [
    { key: '1', name: '张三', age: 32, address: '张庄' },
    { key: '2', name: '王二', age: 42, address: '王桥' },
  ];

  const columns = [
    { title: 'Name', dataIndex: 'name', key: 'name' },
    { title: 'Age', dataIndex: 'age', key: 'age' },
    { title: 'Address', dataIndex: 'address', key: 'address' },
  ];

  const exportToExcel = () => {
    // 创建表头
    const header = columns.map(col => col.title);

    // 创建数据行
    const data = dataSource.map(item =>
      columns.map(col => item[col.dataIndex])
    );

    // 合并表头和数据
    const exportData = [header, ...data];

    // 创建工作簿
    const worksheet = XLSX.utils.aoa_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();

    // 将 sheet 添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

    // 命名根据自己设定,生成 Excel 文件并触发下载,
    XLSX.writeFile(workbook, 'table-data.xlsx');
  };

  return (
    <div>
      <Button onClick={exportToExcel}>导出 Excel</Button>
      <Table dataSource={dataSource} columns={columns} />
    </div>
  );
};

export default TestComponent;
  1. 表头 (header) :使用 columns.map(col => col.title)columns 中提取每一列的 title,作为 Excel 文件的表头。
  2. 数据行 (data) :使用 dataSource.map 来遍历每一行数据,然后使用 columns.map 根据 dataIndex 提取对应的数据值。
  3. aoa_to_sheetxlsx 提供的 aoa_to_sheet 方法用于将二维数组(表头和数据)转换为 Excel 的 sheet 格式。
  4. 合并数据:将表头和数据合并成一个数组,并作为最终导出的 Excel 文件内容。

这样,导出的 Excel 文件中会包含 columns 的表头和 dataSource 的对应数据。

相关推荐
扶苏10023 分钟前
vue使用event.dataTransfer实现A容器数据拖拽复制到到B容器
前端·vue.js·chrome
David凉宸5 分钟前
Vue 3 项目的性能优化策略:从原理到实践
前端·vue.js·性能优化
小马_xiaoen12 分钟前
Proxy 与 Reflect 从入门到实战:ES6 元编程核心特性详解
前端·javascript·ecmascript·es6
hoiii18723 分钟前
MATLAB SGM(半全局匹配)算法实现
前端·算法·matlab
会编程的土豆1 小时前
新手前端小细节
前端·css·html·项目
广州华水科技2 小时前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊2 小时前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12102 小时前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a2 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou2 小时前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单