Export html table to CSV using Javascript

Export html table to CSV using Javascript

The export feature is very useful on data list in a web application. It helps the user to download data list as a file format for offline use. In the web application, CSV is a most used format for exporting data to a file. Export data to CSV is very easy and most important to make your web application user-friendly.

JavaScript Code

function exportTableToCSV($table, filename) {
        var $rows = $table.find('tr:has(td),tr:has(th)'), 
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character
        colDelim = '","',
        rowDelim = '"\r\n"',
        csv = '"' + $rows.map(function (i, row) {
           var $row = $(row), $cols = $row.find('td,th');
           return $cols.map(function (j, col) {
              var $col = $(col), text = $col.text();
              return text.replace(/"/g, '""'); // escape double quotes
           }).get().join(tmpColDelim);
       }).get().join(tmpRowDelim)
          .split(tmpRowDelim).join(rowDelim)
          .split(tmpColDelim).join(colDelim) + '"',
       csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

    if (window.navigator.msSaveBlob) { // IE 10+            
        //alert('IE' + csv);           
         window.navigator.msSaveOrOpenBlob(new Blob([csv], {type: "text/plain;charset=utf-8;"}), "csvname.csv")        
    }  else {          
       $(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' });
    }
}

// This must be a hyperlink
$(document).on('click',"#btnExport", function (event) {
      exportTableToCSV.apply(this, [$('#dynamic-table'), 'exportRawData.csv']);
});

HTML Code

The members HTML table contains some basic users data, like name, email, country.

<table>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>john@gmail.com</td>
        <td>USA</td>
    </tr>
    <tr>
        <td>Stephen Thomas</td>
        <td>stephen@gmail.com</td>
        <td>UK</td>
    </tr>
    <tr>
        <td>Natly Oath</td>
        <td>natly@gmail.com</td>
        <td>France</td>
    </tr>
</table>

On clicking the button, exportTableToCSV() method is called to export table data to CSV file. Also, the desired filename for download CSV file is passed to this function.

<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>

Conclusion

Hope using our minimal JavaScript code you can easily export table data to CSV. You don’t need to user any jQuery plugin or server side script for export data to CSV. Also, you can add table columns and rows based on your requirement.

 

Leave a Reply

Your email address will not be published. Required fields are marked *