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

如何用Ant Design将日期作为列头的表格转换为目标样式

Ant Design 表格改造实现方案

根据你提供的现有表格和目标样式,核心是实现多级分组表头+顶部统一标题栏,以下是具体实现步骤和代码示例:

1. 核心:多级分组表头

利用Ant Design Table的columns.children属性实现表头分组,这是实现目标样式的关键:

import { Table, Button } from 'antd';

// 模拟数据源
const data = [
  { id: 1, name: '张三', dept: '技术部', performance: '95', rating: 'A', key: '1' },
  { id: 2, name: '李四', dept: '技术部', performance: '88', rating: 'B', key: '2' },
  { id: 3, name: '王五', dept: '市场部', performance: '92', rating: 'A', key: '3' },
];

// 定义带分组的表头
const columns = [
  {
    title: '基础信息',
    colSpan: 3,
    children: [
      { title: 'ID', dataIndex: 'id', key: 'id', align: 'center' },
      { title: '姓名', dataIndex: 'name', key: 'name', align: 'center' },
      { title: '部门', dataIndex: 'dept', key: 'dept', align: 'center' },
    ],
  },
  {
    title: '业务数据',
    colSpan: 2,
    children: [
      { title: '业绩', dataIndex: 'performance', key: 'performance', align: 'center' },
      { title: '评级', dataIndex: 'rating', key: 'rating', align: 'center' },
    ],
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    render: () => <Button type="link">查看详情</Button>,
  },
];

// 渲染表格
export default function CustomTable() {
  return (
    <Table
      // 添加顶部统一标题
      title={() => (
        <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '16px', padding: '10px 0' }}>
          员工信息汇总表
        </div>
      )}
      columns={columns}
      dataSource={data}
      bordered
      className="custom-table"
    />
  );
}

2. 样式优化(可选)

如果需要更贴近目标样式的边框、背景色,可添加自定义CSS:

.custom-table .ant-table-thead > tr > th {
  background-color: #f0f2f5;
  border-right: 1px solid #d9d9d9;
}
.custom-table .ant-table-thead .ant-table-cell-grouped {
  border-bottom: 1px solid #d9d9d9;
}
.custom-table .ant-table-tbody > tr > td {
  border-right: 1px solid #d9d9d9;
}

3. 单元格合并(如果目标有此需求)

如果目标表格存在单元格跨行/跨列合并,可在render中返回props设置rowSpan/colSpan:

// 示例:合并相同部门的单元格
const countSameDept = (deptName) => {
  return data.filter(item => item.dept === deptName).length;
};

// 修改部门列的render
{
  title: '部门',
  dataIndex: 'dept',
  key: 'dept',
  align: 'center',
  render: (text, record, index) => {
    const isSameAsPrev = index > 0 && data[index].dept === data[index - 1].dept;
    return {
      children: text,
      props: {
        rowSpan: isSameAsPrev ? 0 : countSameDept(text),
      },
    };
  },
}

内容的提问来源于stack exchange,提问作者Đỗ Thành

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:46:18