Skip to content

Instantly share code, notes, and snippets.

@nobodyplace
Last active August 5, 2021 11:11
Show Gist options
  • Save nobodyplace/accd2677f4abbd67d543ead1538c47af to your computer and use it in GitHub Desktop.
Save nobodyplace/accd2677f4abbd67d543ead1538c47af to your computer and use it in GitHub Desktop.
JavaScriptでデータからCSVファイルを生成しダウンロードさせる
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JavaScriptでデータからCSVファイルを生成しダウンロードさせる</title>
<meta charset="utf-8">
</head>
<body>
<button type="button" onClick="createAndDownloadCsv()">CSVダウンロード</button>
<script>
function createAndDownloadCsv() {
let records = [
['ID','商品名','価格'],
[1, 'スパイスカレー', 1000],
[2, 'おそうざい盛り合わせ', 1200]
];
let bom = new Uint8Array([0xEF, 0xBB, 0xBF]);
let data = records.map((record) => record.join('\t')).join('\r\n');
let blob = new Blob([ bom, data ], { 'type' : 'text/csv' });
let downloadLink = document.createElement('a');
downloadLink.download = 'sample.csv';
downloadLink.href = URL.createObjectURL(blob);
downloadLink.dataset.downloadurl = ['text/plain', downloadLink.download, downloadLink.href].join(':');
downloadLink.click();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment