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

MUI DataGrid实现Excel一键导出:取消下拉菜单直接导出

MUI DataGrid 直接导出Excel(无需下拉菜单)

要实现点击按钮直接导出Excel,无需展开下拉菜单,你可以绕过默认的GridToolbarExport组件,直接调用DataGrid实例的exportDataAsExcel方法,自定义导出按钮。

实现步骤

  • 通过useRef获取DataGrid的实例引用
  • 自定义工具栏组件,添加一个直接触发导出的按钮
  • 将自定义工具栏替换掉DataGrid默认的工具栏

完整代码示例

import React, { useRef } from 'react';
import { DataGrid, GridToolbarContainer } from '@mui/x-data-grid';
import SaveAltIcon from '@mui/icons-material/SaveAlt';
import Button from '@mui/material/Button';

// 自定义工具栏,包含直接导出Excel的按钮
const CustomToolbar = ({ gridRef }) => {
  const handleExport = () => {
    // 调用DataGrid的Excel导出方法
    gridRef.current?.exportDataAsExcel();
  };

  return (
    <GridToolbarContainer>
      <Button
        variant="contained"
        startIcon={<SaveAltIcon />}
        onClick={handleExport}
      >
        导出Excel
      </Button>
    </GridToolbarContainer>
  );
};

export default function DirectExcelExportGrid() {
  const gridRef = useRef(null);

  // 示例列配置和数据
  const columns = [
    { field: 'id', headerName: 'ID', width: 70 },
    { field: 'name', headerName: '姓名', width: 130 },
    { field: 'age', headerName: '年龄', type: 'number', width: 90 },
  ];

  const rows = [
    { id: 1, name: '张三', age: 35 },
    { id: 2, name: '李四', age: 42 },
  ];

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        ref={gridRef}
        rows={rows}
        columns={columns}
        // 指定自定义工具栏组件
        components={{ Toolbar: CustomToolbar }}
        // 传递gridRef给自定义工具栏
        componentsProps={{
          toolbar: { gridRef },
        }}
      />
    </div>
  );
}

自定义导出选项(可选)

如果需要配置导出的文件名、指定导出列、过滤数据等,可以给exportDataAsExcel传入配置参数:

gridRef.current?.exportDataAsExcel({
  fileName: '用户数据.xlsx',
  // 只导出指定列
  columns: ['id', 'name'],
  // 导出前过滤行数据
  getRowsToExport: (rows) => rows.filter(row => row.age > 30),
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:04:58