LoginSignup
0
0

More than 1 year has passed since last update.

TypeScriptで文字列配列からCSVダウンロード

Last updated at Posted at 2021-03-01
  • IE対応。
  • コンマや改行を含むセルは " で囲む。
declare global {
  interface Navigator {
    msSaveBlob?: (blob: any, defaultName?: string) => boolean;
  }
}

function downloadCsvBlob (data: string[][], fileName: string) {
  const bom = new Uint8Array([0xEF, 0xBB, 0xBF]);
  const re = /[,\r\n"]/;
  const csv = data.map(record => record.map(value => re.test(value)
    ? `"${value.replace(/"/g, '""')}"` : value).join(',')).join('\r\n');
  const blob = new Blob([bom, csv], { type: 'text/csv' });

  if (window.navigator.msSaveBlob) { // for IE,Edge
    window.navigator.msSaveBlob(blob, fileName);
  } else {
    const url = URL.createObjectURL(blob);
    const el = document.createElement('a');
    el.href = url;
    el.setAttribute('download', fileName);
    document.body.appendChild(el);
    el.click();
    URL.revokeObjectURL(url);
    if (el.parentNode) {
      el.parentNode.removeChild(el);
    }
  }
}
0
0
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
0