0

I'm trying to export data from an Angular 6 web application.

I have an array of string, where each string is a csv line, formatted like this:

var csvLines = ['val1,val2\n', 'val3,val4\n'...];

Once I've added all the data to i need to the array, i write it to the console:

enter image description here This looks fine...

Now i wan't to convert it to a blob and download it as a .CSV file.

The download is fine, but the format of the output is wrong.

When I run the following code:

          const blob = new Blob([csvLines], {type: 'text/csv;encoding:utf-8'});
          const reader = new FileReader();
          reader.onload = () => {
            console.log(reader.result);
          };
          reader.readAsText(blob);

I get this output.

NOTE the commas that are appended on every line but the first - this mess up my csv. enter image description here

Can anyone tell me why this is happening and perhaps how to disable the comma appending?

I have tried to create the Blob with text/plain as mimetype and without the encoding, but the commas are still appended.

1

1 Answer 1

2

Because you are passing csvLines as [csvLines] to new Blob(..), you are passing an array containing an array. It seems like the subarray is joined using commas. Just use new Blob(csvLines, { type: 'text/csv;encoding:utf-8' }); and you should be fine.

const csvLines = ['val1,val2\n', 'val3,val4\n'];
const blob = new Blob(csvLines, { type: 'text/csv;encoding:utf-8' });
const reader = new FileReader();
reader.onload = () => {
  console.log(reader.result);
};
reader.readAsText(blob);
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.