Javascript: Exporting large text/csv file crashes Google Chrome
Asked Answered
A

2

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)

Arkansas answered 25/4, 2014 at 19:31 Comment(0)
P
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://mcmap.net/q/205971/-export-html-table-to-csv-in-google-chrome-browser

Paraphrast answered 22/9, 2014 at 13:26 Comment(2)
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?Putrescent
I also have no idea why this works. I was using encodeURI function before.Carman
E
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);
        }
}
Electrum answered 15/7, 2016 at 7:12 Comment(3)
Is this compatible with Safari? @ElectrumMedawar
Have not tested this with Safari.Electrum
For those that stumble across this, I tested this solution in all modern browsers (NOT IE, but edge) and it worked perfectly.Gonorrhea

© 2022 - 2024 — McMap. All rights reserved.