跳到主要內容
+

數據網格 - 匯出

輕鬆匯出列,支援 CSV、Excel 或 PDF 等各種檔案格式。

啟用匯出

預設工具列

若要啟用匯出選單,請在 Toolbar 組件 slot 中傳遞 GridToolbar 組件。

按下 Enter 鍵開始編輯

自訂工具列

匯出選單在名為 GridToolbarExport 的獨立組件中提供。您可以在自訂工具列組件中依下列方式使用它。

function CustomToolbar() {
  return (
    <GridToolbarContainer>
      <GridToolbarExport />
    </GridToolbarContainer>
  );
}

匯出選項

預設情況下,匯出選單會根據您的許可證顯示所有可用的匯出格式,包括

您可以透過將選項物件傳遞至 GridToolbarGridToolbarExport 作為 prop 來客製化它們各自的行為。

<DataGrid slotProps={{ toolbar: { csvOptions } }} />

// same as

<GridToolbarExport csvOptions={csvOptions} />

每個匯出選項都有其自己的 API 頁面

已停用的格式

您可以從工具列中移除匯出格式,方法是將其選項屬性 disableToolbarButton 設定為 true。在下列範例中,列印匯出已停用。

<DataGrid
  slotProps={{ toolbar: { printOptions: { disableToolbarButton: true } } }}
/>

已匯出的欄

預設情況下,匯出只會包含 Data Grid 的可見欄。有幾種方法可以包含或隱藏其他欄。

  • 在您不想匯出的欄的 GridColDef 中,將 disableExport 屬性設定為 true
<DataGrid columns={[{ field: 'name', disableExport: true }, { field: 'brand' }]} />
  • 在匯出選項中將 allColumns 設定為 true,以同時包含隱藏欄。 具有 disableExport=true 的欄將不會匯出。
<DataGrid slotProps={{ toolbar: { csvOptions: { allColumns: true } } }} />
  • 在匯出選項中設定要匯出的確切欄。 設定 fields 會覆寫其他屬性。 如此一來,匯出的欄就會與 fields 中的欄完全相同,且順序也相同。
<DataGrid slotProps={{ toolbar: { csvOptions: { fields: ['name', 'brand'] } } }} />

已匯出的列

預設情況下,Data Grid 會匯出選取的列 (如果有的話)。 如果沒有,則會匯出所有列,頁尾除外 (已篩選和排序的列,根據作用中的規則),包括已摺疊的列。

客製化要匯出的列

或者,您可以設定 getRowsToExport 函數並匯出您想要的任何列,如下列範例所示。 網格匯出一些 selector,可協助您取得最常見使用案例的列

選擇器 行為
gridRowIdsSelector 原始順序的列。
gridSortedRowIdsSelector 套用排序規則後的列。
gridFilteredSortedRowIdsSelector 套用排序規則和篩選規則後的列。
gridExpandedSortedRowIdsSelector 套用排序規則、篩選規則且不包含已摺疊列的列。
gridPaginatedVisibleSortedGridRowIdsSelector 套用排序規則、篩選規則、不包含已摺疊列且僅限目前頁面的列 (注意:如果分頁已停用,它仍會採用 pagepageSize 的值)。

當使用列分組時,從 CSV 匯出中移除群組可能很有用。

CSV 匯出

已匯出的儲存格

當欄位的值是物件或提供 renderCell 時,CSV 匯出可能無法正確顯示值。 您可以提供具有字串表示法的 valueFormatter 以供使用。

<DataGrid
  columns={[
    {
      field: 'progress',
      valueFormatter: (value) => `${value * 100}%`,
      renderCell: ({ value }) => <ProgressBar value={value} />,
    },
  ]}
/>

檔案編碼

您可以使用 csvOptions 來指定匯出的格式,例如用於分隔欄位的 delimiter 字元、fileNameutf8WithBom,以在匯出檔案前加上 UTF-8 位元組順序記號 (BOM)。 如需這些選項的更多詳細資訊,請瀏覽 csvOptions API 頁面

<GridToolbarExport
  csvOptions={{
    fileName: 'customerDataBase',
    delimiter: ';',
    utf8WithBom: true,
  }}
/>

逸出公式

預設情況下,儲存格中的公式會逸出。 這是為了防止公式在 在 Excel 中開啟 CSV 檔案 時執行。

如果您想要讓公式繼續運作,可以將 escapeFormulas 選項設定為 false

<DataGrid slotProps={{ toolbar: { csvOptions: { escapeFormulas: false } } }} />

// or

<GridToolbarExport csvOptions={{ escapeFormulas: false }} />

修改 Data Grid 樣式

預設情況下,列印的網格相當於列印僅包含 Data Grid 的頁面。 若要修改用於列印的樣式 (例如色彩),您可以使用 @media print 媒體查詢或 printOptionspageStyle 屬性。

例如,如果 Data Grid 處於深色模式,則文字顏色將不適合列印 (太淺)。

使用 media query,您必須以 @media print 鍵開頭您的 sx 物件,以便僅在列印時套用所有樣式。

<DataGrid
  sx={{
    '@media print': {
      '.MuiDataGrid-main': { color: 'rgba(0, 0, 0, 0.87)' },
    },
  }}
  {/* ... */}
/>

使用 pageStyle 選項,您可以使用 更具體的選擇器 覆寫主要內容顏色。

<DataGrid
  slotProps={{
    toolbar: {
      printOptions:{
        pageStyle: '.MuiDataGrid-root .MuiDataGrid-main { color: rgba(0, 0, 0, 0.87); }',
      }
    }
  }}
  {/* ... */}
/>

客製化網格顯示

預設情況下,列印匯出會顯示所有 DataGrid。 可以分別將 hideFooterhideToolbar 設定為 true 來移除頁尾和工具列。

<GridToolbarExport
  printOptions={{
    hideFooter: true,
    hideToolbar: true,
  }}
/>

如果在匯出時選取了列,則核取方塊將不會包含在列印頁面中。 若要匯出核取方塊,您可以將 includeCheckboxes 設定為 true

<GridToolbarExport
  printOptions={{
    includeCheckboxes: true,
  }}
/>

如需更多客製化列印匯出的選項,請瀏覽 printOptions API 頁面

自訂匯出格式

您可以透過建立自己的匯出選單來新增自訂匯出格式。 若要簡化其建立,您可以使用包含選單邏輯的 <GridToolbarExportContainer />。 預設的 <GridToolbarExport /> 定義如下

const GridToolbarExport = ({ csvOptions, printOptions, ...other }) => (
  <GridToolbarExportContainer {...other}>
    <GridCsvExportMenuItem options={csvOptions} />
    <GridPrintExportMenuItem options={printOptions} />
  </GridToolbarExportContainer>
);

<GridToolbarExportContainer /> 的每個子項都會收到 prop hideMenu,以便在匯出後關閉匯出選單。 下列示範顯示如何新增 JSON 匯出。

Excel 匯出

此功能依賴 exceljs。 Excel 匯出允許將 DataGrid 的欄類型和樹狀結構轉譯為 Excel 檔案。

類型為 'boolean''number''singleSelect''date''dateTime' 的欄會以其在 Excel 中的對應類型匯出。 請確保 rows 值具有正確的類型,您可以隨時在需要時轉換它們

客製化

客製化欄

您可以使用 columnsStyles 屬性來自訂欄樣式。 此屬性接受物件,其中索引鍵是欄位,而值是 exceljs 樣式物件

這可用於指定值格式或新增一些顏色。

<GridToolbarExport
  excelOptions={{
    columnsStyles: {
      // replace the dd.mm.yyyy default date format
      recruitmentDay: { numFmt: 'dd/mm/yyyy' },
      // set this column in green
      incomes: { font: { argb: 'FF00FF00' } },
    },
  }}
/>

客製化文件

您可以使用兩個回呼函數來自訂文件

  • 新增列的資料集之前呼叫 exceljsPreProcess
  • 資料集匯出至文件之後呼叫 exceljsPostProcess

這兩個函數都接收 { workbook, worksheet } 作為輸入。 它們是 exceljs 物件,可讓您直接操作 Excel 檔案。

透過這兩種方法,您可以修改匯出試算表的metadata。 您也可以使用它在工作表的頂端或底部新增自訂內容,如下所示

function exceljsPreProcess({ workbook, worksheet }) {
  workbook.created = new Date(); // Add metadata
  worksheet.name = 'Monthly Results'; // Modify worksheet name

  // Write on first line the date of creation
  worksheet.getCell('A1').value = `Values from the`;
  worksheet.getCell('A2').value = new Date();
}

function exceljsPostProcess({ worksheet }) {
  // Add a text after the data
  worksheet.addRow(); // Add empty row

  const newRow = worksheet.addRow();
  newRow.getCell(1).value = 'Those data are for internal use only';
}

// ...

<GridToolbarExport
  excelOptions={{
    exceljsPreProcess,
    exceljsPostProcess,
  }}
/>;

由於 exceljsPreProcess 是在新增 Data Grid 的內容之前套用,因此您可以使用它在文件頂端新增一些資訊性列。 Data Grid 的內容將從 exceljsPreProcess 新增的列之後的下一列開始。

若要客製化 Data Grid 內容之後的列,您應該使用 exceljsPostProcess。 由於它是在新增內容之後套用,因此您也可以使用它來存取產生的儲存格。

在下列示範中,這兩種方法都用於設定自訂標頭和自訂頁尾。

使用 web worker

您可以將工作委派給 web worker,而不是在主執行緒中產生 Excel 檔案。 此方法減少了主執行緒保持凍結的時間量,允許在資料於背景中匯出時與網格互動。 若要開始將 web worker 用於 Excel 匯出,首先您需要建立一個包含下列內容的檔案。 此檔案稍後將用作 worker 腳本,因此必須可透過直接 URL 存取。

// in file ./worker.ts
import { setupExcelExportWebWorker } from '@mui/x-data-grid-premium/setupExcelExportWebWorker';

setupExcelExportWebWorker();

最後的步驟是將檔案的路徑傳遞至 GridToolbarExport 或 API 方法

<GridToolbarExport
  excelOptions={{
    worker: () => new Worker('/worker.ts'),
  }}
/>;

// or

apiRef.current.exportDataAsExcel({
  worker: () => new Worker('/worker.ts'),
});

由於在匯出資料時主執行緒未鎖定,因此務必為使用者提供正在進行中某些動作的回饋。 您可以將回呼傳遞至 onExcelExportStateChange prop 並顯示訊息或載入器。 下列示範包含使用 Snackbar 的範例

逸出公式

預設情況下,儲存格中的公式會逸出。 這是為了防止公式在 檔案在 Excel 中開啟 時執行。

如果您想要讓公式繼續運作,可以將 escapeFormulas 選項設定為 false

<DataGridPremium slotProps={{ toolbar: { excelOptions: { escapeFormulas: false } } }} />

// or

<GridToolbarExport excelOptions={{ escapeFormulas: false }} />

Clipboard

clipboard 匯出可讓您將 Data Grid 的內容複製到剪貼簿。 如需更多資訊,請查看 Clipboard 複製 文件。

apiRef

網格公開了一組方法,可使用命令式 apiRef 啟用所有這些功能。 若要深入瞭解如何使用它,請查看 API 物件 區段。

CSV

簽章
exportDataAsCsv: (options?: GridCsvExportOptions) => void
簽章
getDataAsCsv: (options?: GridCsvExportOptions) => string
簽章
exportDataAsPrint: (options?: GridPrintExportOptions) => void

Excel

簽章
exportDataAsExcel: (options?: GridExcelExportOptions) => Promise<void>
簽章
getDataAsExcel: (options?: GridExcelExportOptions) => Promise<Excel.Workbook> | null