surya surya - 2 months ago 19
Javascript Question

no newlines in generated CSV

In my page I am writing the following script to generate CSV to download.
My string 'str' has some new line char's "\n" but generated csv is all in one line. am I missing anything?

var fileContent = "data:text/csv;charset=utf-8," + str;
var a = document.createElement('a');
a.href = fileContent;
a.download = filename;
var e = document.createEvent('MouseEvents');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);

Answer

you need to convert the data to base64

in most browsers, it's as simple as

var fileContent = "data:text/csv;charset=utf-8;base64," + btoa(str);

However, if you have a Unicode string, this will fail. Consider this instead - source = http://mdn.beonex.com/en/DOM/window.btoa.html#Unicode_Strings

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
var fileContent = "data:text/csv;charset=utf-8;base64," + utf8_to_b64(str);