Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newline characters in CSV Data URI not showing up

I have a CSV data

column1,column2,column3
data1,data2,data3
data1,data2,data3

I have it as a Jade variable, which is as good as interpolated string as a whole in the HTML, and I make it available for download via a link in Data URI format

var link = document.getElementById('link');
var data = 'column1,column2,column3\n\rdata1,data2,data3\n\rdata1,data2,data3';
link.href = 'data:text/csv,' + data;
<a id="link" download="data.csv">download</a>

I've used Javascript to insert data here for demo, but I'm actually using Jade on server side: (I don't think this makes any different though..)

a(href="data:text/csv,#{data.replace(/[\r\n]/, '\r\n')}" download="data.csv") Download

The problem is the newline character isn't working. When I download the file it doesn't have the newline characters.

In fact wiki says

In Mozilla Firefox 5, Google Chrome 17, and IE 9 (released June, 2011), encoded data must not contain newlines.

This another question, if I'm not misunderstanding, did state that it's possible.

Is it really not possible to have newline for CSV download in Data URI format, or is there a way that I may have missed?

like image 217
laggingreflex Avatar asked Mar 17 '15 17:03

laggingreflex


1 Answers

Nice question asked a long time ago :) I suffered from this problem today as well. For me it works if I URL encode the CSV. So that newline characters "\n" and/or "\r" become "%0A" and "%0D"

var link = document.getElementById('link');
var data = 'column1,column2,column3\n\rdata1,data2,data3\n\rdata1,data2,data3';
data = encodeURI(data);
link.href = 'data:text/csv,' + data;
like image 118
Fedor Petrov Avatar answered Sep 27 '22 19:09

Fedor Petrov