この記事ではmaterial-tableのexportCsvを使って出力するCSVをカスタマイズする方法をご紹介します。
exportCsvは出力するCSVの内容を変更できるオプションプロパティです。
Function to create a custom CSV file
カスタムCSVファイルを作成する機能
https://material-table.com/#/docs/all-props
exportCsvを使ってCSVを出力するには、CSVの出力処理までコードを書く必要があります。
CSVのデータの作り方は同じですが、CSVの出力方法を
- filefyを使わない方法
 - filefyを使う方法
 
の2通りをご紹介します。
filefyとはCSVをダウンロードするJavaScriptライブラリです。
exportCsvでfilefyを使わないCSV出力
CSVの出力部分も組んでいます。
もしCSV出力ライブラリを使用して出力したい場合はfilefyを使った方法を次で紹介します。
useRef()を使ってMaterialTableに定義した内容を使って出力します。
exportCsvでfilefyを使わずにCSV出力のコードの例は以下の通りです。
import React, { useRef } from 'react';
import { render } from 'react-dom';
import MaterialTable from "material-table";
const columns = [...];
const data = [...];
const downloadCsv = (data, fileName) => {
  const finalFileName = fileName.endsWith(".csv") ? fileName : `${fileName}.csv`;
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
  a.setAttribute("download", finalFileName);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
const App = () => {
  const tableRef = useRef();
  return (
    <div>
      <MaterialTable
        tableRef={tableRef}
        data={data}
        columns={columns}
        options={{
          exportButton: true,
          exportCsv: (columns, data) => {
            // ヘッダを文字列の配列に変換
            const headerRow = columns.map(col => (col.title));
            // tableDataを除外してテーブルデータのみの配列にする
            const dataRows = data.map(({ tableData, ...row }) => Object.values(row));
            // optionsのexportDelimiterでしていている区切り文字を取得
            const { exportDelimiter } = tableRef.current.props.options;
            // 区切り文字を指定していなければカンマ
            const delimiter = exportDelimiter ? exportDelimiter : ",";
            const csvContent = [headerRow, ...dataRows].map(e => e.join(delimiter)).join("\n");
            // テーブルのタイトルをファイル名として使う
            const csvFileName = tableRef.current.props.title;
            // CSVとしてファイルをダウンロード
            downloadCsv(csvContent, csvFileName);
          }
        }}
      />
    </div>
  );
}
render(<App />, document.getElementById('root'));exportCsvでfilefyを使ってCSV出力
次にfilefyを使って出力する方法をご紹介します。
filefyはCSVを出力する部分で使います。
A javascript library to produce downloadable files such as in CSV, PDF, XLSX, DOCX formats
CSV、PDF、XLSX、DOCXフォーマットなどのダウンロード可能なファイルを作成するためのJavaScriptライブラリ
https://github.com/mbrn/filefy#readme
まずはfilefyをインストールしてください。
npm install --save filefy
yarn add filefyuseRef()を使ってMaterialTableに定義した内容を使って出力します。
exportCsvでfilefyを使ってCSV出力のコードの例は以下の通りです。
import React, { useRef } from 'react';
import { render } from 'react-dom';
import MaterialTable from "material-table";
const columns = [...];
const data = [...];
const App = () => {
  const tableRef = useRef();
  return (
    <div>
      <MaterialTable
        tableRef={tableRef}
        data={data}
        columns={columns}
        options={{
          exportButton: true,
          exportCsv: (columns, data) => {
            // ヘッダを文字列の配列に変換
            const headerRow = columns.map(col => (col.title));
            // tableDataを除外してテーブルデータのみの配列にする
            const dataRows = data.map(({ tableData, ...row }) => Object.values(row));
            // optionsのexportDelimiterでしていている区切り文字を取得
            const { exportDelimiter } = tableRef.current.props.options;
            // 区切り文字を指定していなければカンマ
            const delimiter = exportDelimiter ? exportDelimiter : ",";
            const csvContent = [headerRow, ...dataRows].map(e => e.join(delimiter)).join("\n");
            // テーブルのタイトルをファイル名として使う
            const csvFileName = tableRef.current.props.title;
            // CSVとしてファイルをダウンロード
            new CsvBuilder(csvFileName)
              .setDelimeter(',')
              .setColumns(headerRow)
              .addRows(dataRows)
              .exportFile();
          }
        }}
      />
    </div>
  );
}
render(<App />, document.getElementById('root'));参考
https://github.com/mbrn/material-table/issues/1916
Reactの参考書をまとめておきます。

	







コメント