I have website that generates data which is then downloaded as a CSV file. The data is originally in an array which I then transform to a CSV file as follows:
var csvData = [['array', 'that'], ['contains', 'csv'], ['data']];
var csv = "";
csvData.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
var csvFile = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
The file looks as expected when opened after downloading using
window.location.href = csvFile;
I'm trying to download multiple CSV in a zip file using JSZip. I have a loop that performs code similar to the code above but instead of downloading each file, I add it to a zip file.
var zip = new JSZip();
for(int i = 0; i < 10; i++) {
var csvData = generateDataArray();
var csv = "";
csvData.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
var csvFile = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
zip.file(`${i}.csv`, csvFile);
}
zip.generateAsync({type:"base64"})
.then(function(content) {
window.location.href = "data:application/zip;base64," + content;
});
My problem is that the CSV files that are in the zip file are not written correctly. All the data is written only on the first line.
This is how the file should look like and how it looks like when downloading outside the zip
This is how the file looks like when it is downloaded in the zip file
I would appreciate any help.
I was able to solve the problem by doing the following:
Instead of using
var csv = "";
csvData.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
var csvFile = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
I used this:
var csvFile = csvData.map(e => e.join(",")).join("\n");
And then I added it to the zip file using:
zip.file(`${i}.csv`, csvFile);
It worked perfectly, but I still don't know why. I would be happy if someone could explain the difference between the two.