Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How To Export HTML Table To CSV With jQuery

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. 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Carsten Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Carsten
Guest
Carsten

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

Carsten