You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React新手求助:如何将表格数据导出为CSV/XLS并实现下载

React 实现表格数据导出为CSV和XLS格式

你的现有代码用原生DOM操作渲染表格,在React项目里更推荐状态驱动UI的方式管理数据,这样导出时直接使用状态中的数据会更方便。下面是完整的实现方案:

完整组件代码

import { useState, useEffect } from 'react';

function EmployeeTable() {
  const [employees, setEmployees] = useState([]);

  // 从API获取数据
  useEffect(() => {
    fetch("http://dummy.restapiexample.com/api/v1/employees")
      .then(res => res.json())
      .then(data => {
        if (data.data.length > 0) {
          setEmployees(data.data);
        }
      })
      .catch(err => console.error('获取数据失败:', err));
  }, []);

  // 导出为CSV
  const exportToCSV = () => {
    // 定义CSV表头
    const headers = ['ID', 'Employee Name', 'Salary'];
    // 转换数据为CSV行(处理特殊字符:用双引号包裹字段)
    const rows = employees.map(emp => [
      `"${emp.id}"`,
      `"${emp.employee_name}"`,
      `"${emp.employee_salary}"`
    ]);
    // 拼接CSV内容
    const csvContent = [
      headers.map(header => `"${header}"`).join(','),
      ...rows.map(row => row.join(','))
    ].join('\n');

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'employees.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 导出为XLS
  const exportToXLS = () => {
    // 构建完整的表格HTML(包含表头和数据)
    const tableHtml = `
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Employee Name</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          ${employees.map(emp => `
            <tr>
              <td>${emp.id}</td>
              <td>${emp.employee_name}</td>
              <td>${emp.employee_salary}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    `;

    // 创建Blob并触发下载
    const blob = new Blob([tableHtml], { type: 'application/vnd.ms-excel;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'employees.xls');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="container">
      {/* 导出按钮 */}
      <div style={{ marginBottom: '1rem' }}>
        <button onClick={exportToCSV} style={{ marginRight: '0.5rem' }}>导出CSV</button>
        <button onClick={exportToXLS}>导出XLS</button>
      </div>
      {/* 员工表格 */}
      <table className="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Employee Name</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          {employees.map(emp => (
            <tr key={emp.id}>
              <td>{emp.id}</td>
              <td>{emp.employee_name}</td>
              <td>{emp.employee_salary}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default EmployeeTable;

关键功能说明

1. 数据管理优化

用React的useState存储员工数据,useEffect在组件挂载时发起API请求,完全遵循React状态驱动模式,避免直接操作DOM,更符合React开发规范。

2. CSV导出逻辑

  • 定义表头数组,将每个员工的字段用双引号包裹(避免逗号等特殊字符破坏CSV格式),再拼接成CSV格式字符串。
  • 通过Blob对象生成CSV文件,创建临时a标签触发浏览器下载,完成后移除标签。

3. XLS导出逻辑

  • 构建包含表头和数据的完整HTML表格字符串,浏览器会自动识别这种格式为Excel文件。
  • 同样通过Blob生成XLS文件,触发下载流程,轻量易实现。

进阶提示

如果需要更复杂的Excel格式(比如单元格样式、多工作表),可以引入xlsx库,但对于基础导出需求,上述方案足够简洁实用。

内容的提问来源于stack exchange,提问作者dev123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:25:46