LoginSignup
3
6

More than 1 year has passed since last update.

JavaScript で table 要素を CSV ファイルに変換する

Last updated at Posted at 2022-05-15

やりたいこと

JavaScript で table 要素を CSV ファイルに変換したい。このとき、クライアント側のみで完結させたい。

方法

// table 要素を 2 次元配列に変換する。
const convertTableToRows = (selector) => {
  const table = document.querySelector(selector);
  const rows = Array.from(table.querySelectorAll('tr')).map(tr => {
    const row = [];
    
    tr.querySelectorAll('th, td').forEach(td => {
      row.push(td.innerText);
      // colspan 属性が設定されている場合は空欄で埋める。
      // なお rowspan 属性は考慮できていない。
      if (td.colSpan && td.colSpan > 1) {
        row.push(...new Array(td.colSpan - 1).fill(''));
      }
    });

    return row;
  });

  return rows;
};

// 2 次元配列を CSV 文字列に変換する。
const convertRowsToCSV = rows => {
  return rows.map(row => row.map(value => `"${value}"`)).join("\n");
};

// CSV ファイルをダウンロードする。
const downloadCSV = (csv, filename) => {
  const csvFile = new Blob([csv], { type: 'text/csv' });

  // ダミーの a 要素を作成してクリックすることでファイルのダウンロードを実現する。
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.download = filename;
  tempLink.href = URL.createObjectURL(csvFile);

  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  
  return filename;
};

const rows = convertTableToRows('table');
const csv = convertRowsToCSV(rows);

downloadCSV(csv, 'order.csv');

Google Chrome を使用します。以下1の赤枠の table 要素を CSV ファイルに変換します。

www_mtgmintcard_com_account-history-info_order_id_537939.png

サイト上で Chrome の開発者ツールを開き、Console タブで前述の JavaScript コードを実行します。そうすると order.csv という CSV ファイルがダウンロードされます。

スクリーンショット 2022-05-15 20.45.56.png

参考

  1. (どうでもいいかもですが) Magic: The Gathering というトレーディングカードゲームのカードを、MTG Mint Card という香港のショップで注文した際の注文履歴です。海外なのに爆速で届きます。スクリーンショットは数ヶ月前のものですが、まだ今ほど円安が進んでいませんでした……。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6