Warning: Undefined array key "show" in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 13
Warning: Undefined variable $bodyClass in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 50
class="post-template-default single single-post postid-259 single-format-standard vertical">

Export HTML table to CSV format

In this blog, you’ll learn how to export HTML table to CSV format without any jQuery plugin.

Add a HTML table in your webpage into the body tag.

<table id="dataTable">
      <td>John Resig</td>
      <td>The Write Less, Do More, JavaScript Library.</td>
      <td>Jordan Walke</td>
      <td>React makes it painless to create interactive UIs.</td>
      <td>Yuxi You</td>
      <td>The Progressive JavaScript Framework.</td>

After table add a link/button for “Click to Download” CSV file.

<a href="#" id="exportcsv" class="work-btn">Export Table data</a>

Install jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Now add code from below to your script tag in HTML file after jQuery installation or in your js file.

$(document).ready(function () {
    function exportTableToCSV($table, filename) { 
        var $rows = $table.find('tr:has(td),tr:has(th)'),
        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character
        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',
        // Grab text from table into CSV formatted string
        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

            .split(tmpColDelim).join(colDelim) + '"',   
        // Data URI
        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
    $("#exportcsv").on('click', function (event) {
        exportTableToCSV.apply(this, [$('#dataTable'), 'export.csv']); 
        // IF CSV, don't do event.preventDefault() or return false
        // We actually need this to be a typical hyperlink

You can use this code for your PHP, WordPress, ASP .NET etc language or basic HTML file.

Thanks for the reading this blog.

Tags: CSV, HTML, jQuery