Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export to CSV with Javascript

I have two functions

  1. Exports HTML Table
  2. Download CSV file

Unfortunately my file is downloading as "Undefined" with no .csv file type.

The format seems to be fine, since the file can be opened with any text editor and can be seen to have all table data with a comma as a delimitter. Which makes it easy for Excel to take in the file and seperate each column and row.

But I need the file to download with the .csv file extension.

Here are my two functions:

function exportTableToCSV(html, filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");

    for(var i = 0; i < rows.length; i++){
        var row = [], cols = rows[i].querySelectorAll("td, th");
        for(var j = 0; j < cols.length; j++){
            row.push(cols[j].innerText);
        }
        csv.push(row.join(","));
    }

    // download csv file
    downloadCSV(csv.join("\n"), filename);
}

function downloadCSV(csv, filename) {
   	    var csvFile;
	var downloadLink;

	csvFile = new Blob([csv], {type:"text/csv"});
	downloadLink = document.createElement("a");
	downloadLink.download = filename;
	downloadLink.href = window.URL.createObjectURL(csvFile);
	downloadLink.style.display = "none";
	document.body.appendChild(downloadLink);
	downloadLink.click();
}

exportTableToCSV('', 'test.csv');

I believe the issue lies with 'function downloadCSV'. Any help or links to some current working examples are highly appreciated.

like image 413
kris_needs_help Avatar asked Oct 17 '22 23:10

kris_needs_help


1 Answers

Did you pass filename to exportTableToCSV like:

exportTableToCSV(null,'test.csv')

See https://jsfiddle.net/mdearman/d1zpndcu/

In some quick testing, it works in Chrome, but not IE (for what its worth).

like image 59
Mike Dearman Avatar answered Oct 21 '22 06:10

Mike Dearman