6

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.

2
  • Your code appears to work fine, what browser are you using? Commented Feb 5, 2018 at 19:32
  • how can we tweak this to handle " in the strings? Commented Aug 12, 2022 at 3:50

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

4 Comments

i see it working in jsfiddle. Nothing different from my code, yet my site is still downloading "undefined". And yes filename is being passed in properly. Maybe this is some sort of server issue? Could that be possible? there shouldnt be any JS libraries needed for this correct?
Nothing I can think of. Perhaps some kind of security zone issue? Or related to the "content" of the CSV file, could there be some kind of MIME sniffing going on? But I wouldn't think that would give you an undefined.
my error was in the way I called 'exportTableToCSV'. I was doing exportTableToCSV('filename.csv') without passing in the first parameter. Wow what a dunst! Thanks so much Mike for your help!
You're welcome, ya, I saw the "html" parameter was unused.

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.