41

I have the following Javascript code to export CSV file on the client side. However Google Chrome crashes every time I try to export a large array. What is the limit of the data string allowed in Chrome? Is it possible that it is hitting the memory limit allowed in Chrome? If the data string is too long for Chrome, how will I go about exporting large CSV files on the client side?

var csvRows = [...]; //Array with 40000 items, each item is 100 characters long.

var csvString = csvRows.join("\r\n");

var a = document.createElement('a');

a.href        = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'export.csv';

document.body.appendChild(a);
a.click();

(Expected file size is about 6.4MB)

Ben Wong
  • 1,987
  • 2
  • 19
  • 20

2 Answers2

66

had the same Problem and solved it using Blob.

For example:

csvData = new Blob([csvString], { type: 'text/csv' }); 
var csvUrl = URL.createObjectURL(csvData);
a.href =  csvUrl;

Source: https://stackoverflow.com/a/24611096/3048937

Community
  • 1
  • 1
jan
  • 806
  • 8
  • 8
  • I have a similar problem, which is to write .xlsx file data created by excelbuilder.js's `EB.createFile()` function. When it has 8000+ records in the table, the browser crashes. I am trying to save it as a blob. However, what is written in file turns out to be the base64 string rather than the excel file data. I've tried different type strings. Do you have any idea? – gm2008 Jan 25 '16 at 12:50
  • I also have no idea why this works. I was using `encodeURI` function before. – Xin Nov 08 '18 at 02:56
13

I used following function to download CSV. Worked for me in IE/Firefox/Chrome

function downloadFile(data, fileName) {
        var csvData = data;
        var blob = new Blob([ csvData ], {
            type : "application/csv;charset=utf-8;"
        });

        if (window.navigator.msSaveBlob) {
            // FOR IE BROWSER
            navigator.msSaveBlob(blob, fileName);
        } else {
            // FOR OTHER BROWSERS
            var link = document.createElement("a");
            var csvUrl = URL.createObjectURL(blob);
            link.href = csvUrl;
            link.style = "visibility:hidden";
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
}
Ganesh
  • 131
  • 1
  • 4