Reputation: 488
I am doing a CSV export using jquery.
My values have special characters in them. Also I need to use the separator as semi-colon.
My code is:
var array= [];
array.push("Item;Name;Value");
array.push("1;Test,1;Test § 17");
array.push("2;Test2;Test § 18");
var csvAudit = [];
for (var i = 0; i < array.length; i++) {
csvAudit.push(array[i]);
}
var csvExport = csvAudit.join('\n');
var csvFileName = "test.csv";
var contentType = 'text/csv;charset=utf-16';
csvExport = "\ufeff" + 'sep=;\r\n' + csvExport;
var csvFile = new Blob([csvExport], {
type: contentType
});
var a = document.createElement('a');
a.download = csvFileName;
a.href = URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
a.click();
When I download the CSV using Chrome browser then, in my excel file I see: Test § 17 instead of Test § 17
If I remove the 'sep=;\r\n' then the special character  is escaped but the separator is used as comma and it shows data in wrong way, i.e., Test, 1 are displayed in separate cell instead of one.
Is there any possible solution to fix this?
Upvotes: 0
Views: 859
Reputation: 488
Finally I was able to resolve the issue by quoting the values in array in double quotes and removed the semi-colon separator and used comma separator instead.
The correct code is:-
var array= [];
array.push(""Item","Name","Value"");
array.push(""1","Test,1","Test § 17"");
array.push(""2","Test2,"Test § 18"");
var csvAudit = [];
for (var i = 0; i < array.length; i++) {
csvAudit.push(array[i]);
}
var csvExport = csvAudit.join('\n');
var csvFileName = "test.csv";
var contentType = 'text/csv';
csvExport = "\ufeff" + csvExport;
var csvFile = new Blob([csvExport], {
type: contentType
});
var a = document.createElement('a');
a.download = csvFileName;
a.href = URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
a.click();
Special character  was removed by appending "\ufeff"
Upvotes: 1