JaeYeopHan / tip-archive

📦 Archiving various development tips. If you watch this repository, you can get issues related to the newly registered development tip from the GitHub feed.
https://www.facebook.com/Jbee.dev/
245 stars 8 forks source link

Export csv file with UTF-8 #61

Open JaeYeopHan opened 4 years ago

JaeYeopHan commented 4 years ago
function downloadObjectAsCSV(exportData, fileName){
  const universalBOM = "\uFEFF";
  const dataset = "data:text/csv;charset=utf-8," + encodeURIComponent(universalBOM+exportData)

  const downloadAnchorNode = document.createElement('a')

  downloadAnchorNode.setAttribute("href", dataset);
  downloadAnchorNode.setAttribute("download", fileName + ".csv")
  document.body.appendChild(downloadAnchorNode)
  downloadAnchorNode.click()
  downloadAnchorNode.remove()
}

위 코드에서 핵심은 universalBOM

.csv 파일을 Excel로 import 하다보면 한글이 깨지는데 BOM을 통해서 해결할 수 있다.