0

I have a simple function that downloads browser data to CSV:

// 3 cols, 2 rows
var data = '"a b c", "d, e, f", "g, h, i" %0A "a b c", "d, e, f", "g, h, i"';

var a = document.createElement('a');
a.href = 'data:attachment/csv;charset=utf-8,' + data;
a.target = '_blank';
a.download = 'labels.csv';
document.body.appendChild(a);
a.click();

This works great, and I get a CSV file. However, when viewing the download file, the results collapse the spaces in each cell:

abc def ghi
abc def ghi

When I view the generated a tag, the spaces are still there, so the download/conversion to .csv is what degrades it.

I cannot figure out or find anything on how to ensure the spaces don't collapse like that. What sort of escape/encoding can I use?

--

This guy here had the same problem (spaces removed) with no working solution.

Community
  • 1
  • 1
dthree
  • 19,847
  • 14
  • 77
  • 106

1 Answers1

1

Okay, I figured it out.

When assembling the data, you have to escape each row separately, and that seemed to do the trick:

for (var i = 0; i < rows.length; ++i) {
  rows[i] = escape(rows[i]);
}
a.href = rows.join('%0A');
dthree
  • 19,847
  • 14
  • 77
  • 106