How To Export HTML Table To CSV With jQuery

In your daily tasks sometimes you need to export some data to a file format the most used being PDF, Excel or CSV. Today, in this tutoial I will show you how to export a html table to csv using just javascript. With few lines of jquery we will create a CSV file and we will autodownload for the user when he request it. Anyway there are a lot of methods for exporting file but in this tutorial we will talk about only about this method using jquery.

To export any html table to CSV use the following 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 = jQuery(row), $cols = $row.find('td,th');
    
                return $cols.map(function (j, col) {
                    var $col = jQuery(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) + '"',
    
            
    
            // Data URI
            csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
            
            console.log(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 {
        		jQuery(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); 
        	}
    }

 

As you can see in the above function it's not so long so is very easy to understand it. Anyway this is only the function and we need a trigger to call this function, so let's say we want to generate this excel when a certain button is pressed. To do this we will use the following click event function:

jQuery(".export_csv").on('click', function (event) { 
        exportTableToCSV.apply(this, [jQuery('.dataTable'), 'export.csv']);
        window.location.reload();
    });

When the button with class export_csv is clicked the function is called, the last parameter is the name of the file which will be created and autodownloaded for the user which clicked the button. The function is tested and everything works great, however, I have tested it only for max 100 <tr> but I guess there will be no problem for more rows, anyway if some problems will occur, please let us a comment and we will try to help you. In the next tutorials I will come back with a new method to export data to Excel, csv and pdf using PHP. 

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Carsten
Carsten
5 years ago

This did not work for me. It gets all the data, but no download. No reaction in Chrom, Firefox nor IE11

Carsten

Mukesh
Mukesh
4 years ago

Hi, this works great! however if I refresh the table with new results via AJAX the export functionality doesn’t work. If I refresh the page completely it works. Any suggestions?

2
0
Would love your thoughts, please comment.x
()
x