如何用@progress/kendo-react-excel-export导出分组数据至Excel(无Grid组件)
使用
@progress/kendo-react-excel-export导出嵌套分类数据为合并单元格样式Excel 步骤1:预处理原始数据
原始数据中每个产品对应一条独立的分类记录,需要先将同分类的产品聚合到一起,方便后续生成合并单元格:
const rawData = [ { "Category": { "CategoryID": 1, "CategoryName": "Beverages", "Product": [{"ProductID": 1,"ProductName": "Chai"}] } }, { "Category": { "CategoryID": 1, "CategoryName": "Beverages", "Product": [{"ProductID": 2,"ProductName": "Chang"}] } } ]; // 按分类ID聚合,合并同分类下的产品列表 const aggregatedData = rawData.reduce((acc, item) => { const currentCat = item.Category; const existingCat = acc.find(cat => cat.CategoryID === currentCat.CategoryID); if (existingCat) { existingCat.Product.push(...currentCat.Product); } else { acc.push({...currentCat}); } return acc; }, []);
步骤2:用ExcelExport构建导出表格
通过自定义HTML表格,利用rowspan属性实现分类单元格的跨行合并,ExcelExport会自动识别这些HTML属性并转化为Excel的合并单元格效果:
import React from 'react'; import { ExcelExport } from '@progress/kendo-react-excel-export'; import { Button } from '@progress/kendo-react-buttons'; export default function CategoryProductExcelExport() { const exportRef = React.useRef(null); const triggerExport = () => { exportRef.current?.save(); }; return ( <div> <Button onClick={triggerExport}>导出Excel</Button> <ExcelExport ref={exportRef} fileName="分类产品清单.xlsx" > <table border="1" cellPadding="8"> <thead> <tr> <th>分类ID</th> <th>分类名称</th> <th>产品ID</th> <th>产品名称</th> </tr> </thead> <tbody> {aggregatedData.map(category => ( category.Product.map((product, index) => ( <tr key={product.ProductID}> {/* 仅分类下第一个产品渲染分类单元格,并设置跨行数为产品总数 */} {index === 0 && ( <> <td rowSpan={category.Product.length}>{category.CategoryID}</td> <td rowSpan={category.Product.length}>{category.CategoryName}</td> </> )} <td>{product.ProductID}</td> <td>{product.ProductName}</td> </tr> )) ))} </tbody> </table> </ExcelExport> </div> ); }
核心说明
- 数据聚合是关键:确保每个分类只对应一组产品,这样才能准确计算
rowspan的数值(即该分类下的产品数量)。 - 依赖HTML表格属性:
ExcelExport支持将HTML表格的rowspan/colspan直接转换为Excel的单元格合并,完全不需要使用kendo-react-grid组件。 - 自定义样式:可以通过HTML表格的
border、cellPadding等属性调整导出后的Excel单元格样式,贴近示例图效果。
内容的提问来源于stack exchange,提问作者alexandr2006
相关产品推荐
相关产品推荐

