0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptでcsvダウンロードを実装する方法

Last updated at Posted at 2021-07-21

#はじめに
フロント(React)でcsvダウンロードを実装する機会があったため、備忘録です。
どうぞご活用ください。

#実装


  const handleDLcsv = async () => {
    //アイテムの定義
    const download_items = [
            {'id': 1, 'name': 'apple', 'price': 100},
            {'id': 2, 'name': 'orange', 'price': 120},
            {'id': 3, 'name': 'melon', 'price': 800}
    ];
    //csvヘッダー
    const array_data = [['id', 'name', 'price']];

    //文字コード
    const bom = new Uint8Array([0xEF, 0xBB, 0xBF]);

    //csv用データ作成
    download_items.map((item) => {
      const item_data = [item.id, item.name, item.price];
      array_data.push(item_data);
    })
    let csv_data = array_data.map(function(l){return l.join(',')}).join('\r\n');

    //BLOB生成してダウンロード実行
    const blob = new Blob([bom, csv_data], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'csv_file.csv';
    const clickHandler = () => {
      setTimeout(() => {
        URL.revokeObjectURL(url);
        a.removeEventListener('click', clickHandler);
      }, 150);
    };
    a.addEventListener('click', clickHandler, false);
    a.click();
  }

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?