useExcelExport

前端 Excel 导出 Hook,支持单级表头、多级表头、表头映射、部分列导出,以及同步/异步数据源。

基本信息

  • 引入import { useExcelExport } from '@resin-hooks/core';
  • 类型useExcelExport(options?: UseExcelExportOptions): UseExcelExportReturn
  • 依赖:基于 SheetJS (xlsx) 实现

特性

  • 单级表头headersMap 将英文字段映射为中文表头
  • 多级表头headers 支持多级分组,自动合并单元格
  • 部分列导出colums 指定导出的列
  • 数据源灵活:支持直接传入数组或 () => Promise<data[]> 异步函数
  • 进度与状态progressloadingerrorInfo 便于 UI 展示

参数

参数 类型 默认值 说明
options UseExcelExportOptions {} 可选配置项

UseExcelExportOptions

属性 类型 默认值 说明
fileName string '导出数据' 导出文件名(含 .xlsx 后缀由 Hook 自动添加时可不带)
sheetName string 'Sheet1' 工作表名
headersMap Record<string, string> - 字段 key → 表头文案,如 { txnId: '交易流水号' }
colums string[] - 要导出的列(字段 key 数组),不传则按数据第一行全部导出
headers ExcelHeader[] - 多级表头配置,传入时启用多级表头

ExcelHeader(多级表头)

1type ExcelHeader = {
2  label: string; // 表头显示文字
3  key?: string; // 对应字段(仅叶子节点需要)
4  children?: ExcelHeader[];
5};

叶子节点需要 key 对应数据字段;非叶子节点用 label 作为分组标题,通过 children 嵌套。

返回值

属性 类型 说明
exportExcel (data: Record<string,unknown>[] | () => Promise<...>) => Promise<void> 执行导出,传入数据数组或返回数据的异步函数
loading boolean 是否正在导出
errorInfo Error | null 错误信息
progress number 导出进度 0-100

使用示例

基本用法(单级表头)

1import { useExcelExport } from '@resin-hooks/core';
2
3function ExportButton() {
4  const { exportExcel, progress, loading, errorInfo } = useExcelExport({
5    fileName: '交易流水.xlsx',
6    headersMap: {
7      txnId: '交易流水号',
8      txnDate: '交易日期',
9      amount: '交易金额',
10    },
11  });
12
13  const handleExport = () => {
14    exportExcel(async () => {
15      const res = await fetch('/api/export?type=transactions&count=1000');
16      const { data } = await res.json();
17      return data;
18    });
19  };
20
21  return (
22    <div>
23      <button onClick={handleExport} disabled={loading}>
24        导出
25      </button>
26      {loading && <progress value={progress} max={100} />}
27      {errorInfo && <p>错误:{errorInfo.message}</p>}
28    </div>
29  );
30}

传入静态数组

1const data = [
2  { id: 1, name: '张三', amount: 100 },
3  { id: 2, name: '李四', amount: 200 },
4];
5
6const { exportExcel } = useExcelExport({
7  fileName: '列表.xlsx',
8  headersMap: { id: 'ID', name: '姓名', amount: '金额' },
9});
10
11exportExcel(data);

仅导出部分列

1// 后端返回多字段,只导出指定列
2const { exportExcel } = useExcelExport({
3  fileName: '交易流水.xlsx',
4  headersMap: TRANSACTIONS_COLUMNS,
5  colums: [
6    'txnId',
7    'txnDate',
8    'type',
9    'amount',
10    'balance',
11    'counterpartyName',
12    'status',
13  ],
14});
15
16exportExcel(async () => {
17  const { data } = await fetch('/api/export').then((r) => r.json());
18  return data;
19});

多级表头

1import { useExcelExport, type ExcelHeader } from '@resin-hooks/core';
2
3const headers: ExcelHeader[] = [
4  {
5    label: '基本信息',
6    children: [
7      { label: '姓名', key: 'name' },
8      { label: '年龄', key: 'age' },
9      {
10        label: '工作信息',
11        children: [
12          { label: '部门', key: 'department' },
13          { label: '薪资', key: 'salary' },
14        ],
15      },
16    ],
17  },
18  {
19    label: '联系方式',
20    children: [
21      { label: '手机', key: 'phone' },
22      { label: '邮箱', key: 'email' },
23    ],
24  },
25];
26
27const { exportExcel } = useExcelExport({
28  fileName: '员工列表.xlsx',
29  headersMap: {
30    name: '姓名',
31    age: '年龄',
32    department: '部门',
33    salary: '薪资',
34    phone: '手机',
35    email: '邮箱',
36  },
37  headers,
38});
39
40exportExcel(employeesData);

设计思路

  1. headersMap:后端用英文字段,导出需中文表头,传入 headersMap 做字段 → 表头映射。
  2. colums:后端返回多字段,只导出部分时,传入 colums 限定导出列。
  3. headers:需要分组表头(如「基本信息 / 工作信息」)时,使用 headers 定义多级结构,由 Hook 自动处理合并单元格。
  4. 数据源:支持 exportExcel(data[]) 同步数据或 exportExcel(async () => data[]) 异步拉取,适应不同业务场景。

使用场景

  • 后台管理系统:列表页导出 Excel,支持筛选条件、自定义列
  • 报表导出:将接口数据导出为 Excel 供离线查看
  • 多级表头报表:财务、人事等需要分组表头的导出场景

注意事项

  • 需要安装 xlsx 依赖(@resin-hooks/core 已包含)
  • 异步数据源需在 exportExcel 调用时传入函数,确保每次导出可获取最新数据
  • 多级表头模式下,headers 中叶子节点必须提供 key,且 key 需与数据字段一致