[Javascript] HTML to CSV – Charset UTF-8 BOM – 完美匯出CSV

使用情境

Javascript在匯出EXCEL有ASCII Code瓶頸不能完美支援,所以匯出CSV是較佳的選擇。

CSV匯出的亮點會在於Charset,例如支援中文而使用BOM。


技術亮點

var csvContent = "欄位A,欄位B\n值A,值B";

var link = window.document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent));
link.setAttribute("download", "upload_data.csv");
link.click();

其中Link格式,使用UTF-8 with BOM:

"data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent)

JSFiddle

One thought on “[Javascript] HTML to CSV – Charset UTF-8 BOM – 完美匯出CSV

Leave a Reply

Your email address will not be published. Required fields are marked *