1

I'm generating a CSV file from an array of data using JS.

My data before the download is this:

var csv =
"Date,valA,valB,valC,valD,AVG
2016-07-01 12:00,393917,211,38534,640,9.78%,
2016-07-01 01:00,342278,171,38131,547,11.14%,
2016-07-01 02:00,265238,168,29395,547,11.08%,";

Every line has a line break character in the end ("\n").

I then add the mime type at the beginning of the string:

csv = 'data:text/csv;charset=utf-8,' + csv;,

and then encode & download:

data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();

Everything works fine, but In the final file there is an empty column for some reason.

I've looked into this question but it is far too detailed. I think the solution here could be very simple.

What am I doing wrong here?

1 Answer 1

1

It turns out that the fact that every line had a comma (",") just before the line break caused the extra trailing column.

All I had to do is make sure my lines end just with a new line character.

The csv string should be:

var csv =
"Date,valA,valB,valC,valD,AVG
2016-07-01 12:00,393917,211,38534,640,9.78%
2016-07-01 01:00,342278,171,38131,547,11.14%
2016-07-01 02:00,265238,168,29395,547,11.08%";

(notice no trailing commas).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.