JavaScript CSV Export with Unicode Symbols
There are often problems exporting unicode symbols to CSV file format. Developers tend to forget to add the UTF-8 BOM at the start of text and text is displayed incorrectly when opened in Excel application. Therefore I add a small example of such an export which might be useful for developers who have come to that problem too.
<script text="text/javascript">
function createExportHeader(dataSource, separator) {
var headerRow = "",
columns = dataSource.columns,
newLine = "\r\n";
for (var i=0; i < columns.length; i++) {
headerRow += (i > 0 ? separator : '') + columns[i].displayName;
}
return headerRow + newLine;
}
function createExportRows(dataSource, separator) {
var content = "",
columns = dataSource.columns,
data = dataSource.data,
newLine = "\r\n",
dataField;
for(var j=0; j < data.length; j++) {
for (var i=0; i < columns.length; i++) {
dataField = columns[i].dataField;
content += (i > 0 ? separator : '') + data[j][dataField];
}
content += newLine;
}
return content;
}
function excelExport() {
var separator = ',',
dataSource = {
data: [
{
name: "Frank Über",
age: 49
},
{
name: "Toni Köhl",
age: 56
}
],
columns: [
{
dataField: "name",
displayName: "Name"
},
{
dataField: "age",
displayName: "Alter"
}
]
};
var content = createExportHeader(dataSource, separator);
content += createExportRows(dataSource, separator);
//an anchor html element on the page (or create dynamically one)
//to use its download attribute to set filename
var a = document.getElementById('csv');
a.textContent='download';
a.download="MyFile.csv";
a.href='data:text/csv;charset=utf-8,%EF%BB%BF'+encodeURIComponent(content);
a.click();
}
</script>
