How to export HTML table to CSV using jQuery

Before coming across the table2CSV library I had to export the data present in the HTML table using server side code. I had to first make the CSV string and then needed to output it on the browser so that the user could download it. Now with the table2CSV it’s just a matter of 3-4 lines and you will be able to export your HTML table without having to write any server side code rather your presentation layer generate it and outputs it to the user thereby saving a lot of server CPU cycles. Check out the code below

  1. Before starting download the table2CSV.js from this website.
  2. Next add the jquery.js and the table2CSV.js in the head portion of your web page.
  3. Now add an id to your HTML table whose data you wish to export to CSV. For this example I will use “exportcsv”.
  4. Finally put a button and add the following code to it’s onclick event.
function getCSVData(){
	 var csv_value=$('#exportcsv').table2CSV({delivery:'value'});
	 $("#csv_text").val(csv_value);	
}

A complete working example for this would be as follows




 

function getCSVData(){
	 var csv_value=$('#exportcsv').table2CSV({delivery:'value'});
	 $("#csv_text").val(csv_value);	
}


Title Name Phone
Mr Adeel 123 456 7890
Mr Amul 098 765 4321
Miss Ranjha 333 333 4456

Please follow and like us:

5 Comments

  1. hi it’s not working, i think full code is not posted.

    if i click one button not showing any event.

    I have one doubt in above code script what is this line

    “$(“#csv_text”).val(csv_value);”

    in that where can i give the ‘#csv_text’ this id name.

    Thanks for advance…

Leave a Reply

Your email address will not be published.


*