2
4

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出力

Posted at

多次元配列からBOM付きUTF-8で出力

 export const downloadCSV = (rows, fileName = 'download') => { 
     const bom = new Uint8Array([0xEF, 0xBB, 0xBF]) 
     const blob = new Blob([ bom, rows.join('\r\n') ], { type : 'text/csv' }) 
     const element = document.createElement('a') 
     const objectUrl = window.URL.createObjectURL(blob)
     element.href = objectUrl 
     element.setAttribute('download', fileName); 
     document.body.appendChild(element) 
     element.click() 
     window.URL.revokeObjectURL(objectUrl) 
     document.body.removeChild(element) 
 } 

利用例


downloadCSV([[11, 12, 13], [21, 22, 23]], 'csvTest')

APIから受け取ったCSVデータを出力

export const downloadCSV = (csv, fileName = 'download') => {
    const blob = new Blob([csv], { type : 'text/csv' })
    const element = document.createElement('a')
    const objectUrl = window.URL.createObjectURL(blob)
    element.href = objectUrl
    element.setAttribute('download', fileName);
    document.body.appendChild(element)
    element.click()
    window.URL.revokeObjectURL(objectUrl)
    document.body.removeChild(element)
} 

利用例

axios.get('/get/csv', { responseType: 'blob' })
    .then(resp => {
        downloadCSV(resp.data, 'csvTest')
    })

responseType: 'blob' を指定しない場合、文字コードが SHIFT-JIS などのデータの時に文字化けする。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?