Last active
August 5, 2021 11:11
-
-
Save nobodyplace/accd2677f4abbd67d543ead1538c47af to your computer and use it in GitHub Desktop.
JavaScriptでデータからCSVファイルを生成しダウンロードさせる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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