jQuery - download csv from a table

1.1k views Asked by At

I am trying to download my html table as a cvs file. The code I have is working however, it is downloading a file called 'unknown' without extension '.csv'. If I add the extension manually the csv file is showing everything correctly apart the first line that is containing also html code (see picture attached)

enter image description here

What am I doing wrong?

this is the script:

$("#btnExport ").on('click', function (event) {

            //Get table
        var table = $(".my-table")[0];

        //Get number of rows/columns
        var rowLength = table.rows.length;
        var colLength = table.rows[0].cells.length;

            console.log(rowLength, colLength);

        //Declare string to fill with table data
        var tableString = "";

        //Get column headers
        for (var i = 0; i < colLength; i++) {
            tableString += table.rows[0].cells[i].innerHTML.split(",").join("") + ",";
        }

        tableString = tableString.substring(0, tableString.length - 1);
        tableString += "\r\n";

        //Get row data
        for (var j = 1; j < rowLength; j++) {
            for (var k = 0; k < colLength; k++) {
                tableString += table.rows[j].cells[k].innerHTML.split(",").join("") + ",";
            }
            tableString += "\r\n";
        }

        //Save file
        if (navigator.appName == "Microsoft Internet Explorer") {
            //Optional: If you run into delimiter issues (where the commas are not interpreted and all data is one cell), then use this line to manually specify the delimeter
             tableString = 'sep=,\r\n' + tableString;

             myFrame.document.open("text/html", "replace");
             myFrame.document.write(tableString);
             myFrame.document.close();
             myFrame.focus();
             myFrame.document.execCommand('SaveAs', true, 'data.csv');
         } else {
            csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(tableString);
             $(event.target).attr({
                 'href': csvData,
                 'target': '_blank',
                 'download': 'my_data.csv'
             });
         }

    });
2

There are 2 answers

4
depperm On

Here is an alternate way to get csv from a table

csvVar='';
$('#<tableID> tr').each(function(){
  var len=$(this).find('td,th').length;
  i=0;
  $(this).find('td,th').each(function(){
    var cell=$(this);
    if(cell.children().prop('tagName') == 'INPUT')
      csvVar+=cell.children().val();
    else if(cell.children().prop('tagName') == 'SELECT')
      csvVar+=$('select option[value="'+cell.children().val() +'"]').html();
    else{
      t=cell.html();
      if(t.indexOf('<br>')>0)
        csvVar+=t.substring(0,t.indexOf('<br>'));
      else if(t.indexOf(',')>0)
        csvVar+=t.replace(',',';');
      else
        csvVar+=t;
    }
    if(i+1<len)
      csvVar+=',';
    i++;
  });
  csvVar+='\n';
});

--EDIT--

var textFileAsBlob = new Blob([csvVar], {type:'text/plain'});
var fileNameToSaveAs = 'whateverTable.csv';

var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.URL != null)
{
  // Chrome allows the link to be clicked
  // without actually adding it to the DOM.
  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
}
else
{
  // Firefox requires the link to be added to the DOM
  // before it can be clicked.
  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  downloadLink.onclick = destroyClickedElement;
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);
}

downloadLink.click();
2
Md Johirul Islam On

Use this function

 function download(strData, strFileName, strMimeType) {
            var D = document,
                a = D.createElement("a");
                strMimeType= strMimeType || "application/octet-stream";


            if (navigator.msSaveBlob) { // IE10
                return navigator.msSaveBlob(new Blob([strData], {type: strMimeType}), strFileName);
            } /* end if(navigator.msSaveBlob) */


            if ('download' in a) { //html5 A[download]
                a.href = "data:" + strMimeType + "," + encodeURIComponent(strData);
                a.setAttribute("download", strFileName);
                a.innerHTML = "downloading...";
                D.body.appendChild(a);
                setTimeout(function() {
                    a.click();
                    D.body.removeChild(a);
                }, 66);
                return true;
            } /* end if('download' in a) */


            //do iframe dataURL download (old ch+FF):
            var f = D.createElement("iframe");
            D.body.appendChild(f);
            f.src = "data:" +  strMimeType   + "," + encodeURIComponent(strData);
            setTimeout(function() {
                D.body.removeChild(f);
            }, 333);
            return true;
        }

Then call the function as you need. I called on a button click. Here is the code

<button type="button" class="btn btn-warning btn-medium" id="download" style="color: white; font-weight: bold; background-color: #2175AD; border-bottom-color: #2175AD; margin-bottom: 100px;">Download table As CSV</button>
            <script>
            $("#download").on("click",function(){
                //$("#eventsMax").table2CSV();
                var mintime= d3.min(curdata,function(d){return d.time;});
                var maxtime= d3.max(curdata,function(d){return d.time;});
                var text="\t\t\t\t\t\t\tHere is the Data From "+mintime+" to "+maxtime+"\n\n";
                var csv = $("#eventsMax").table2CSV({delivery:'value'});
                csv=text+csv;
                download(csv, "realtimeData.csv", "text/csv");
            });

Don't forget to include the API table2CSV.js from http://www.kunalbabre.com/projects/table2CSV.php