Sibeesh Passion

Export From HTML Table Using jQuery

  • 1
  • 1
  • 1

In this article we will see how to export from an HTML table using jQuery. We all work in some applications where we are playing with data’s . It might be some data returned by the server or it might be some client side data like HTML table. No matter which ever form the data is, there will be an export option. Isn’t it? 80% of our clients need the data to be exported as excel. So we need to give the option to export the given data to excel, not dependent of the data format. In my case my data is in the form of an HTML table, so in this post we will explain how to export an html data to excel, pdf, png, jpeg etc. I hope you will like it.

Download Files here : HTML Table Export


As I said earlier, this article explains how to export a HTML table using jQuery. In this article we will see how we can export the given data to the following formats:

  • Excel
  • PDF
  • Image
  • CSV
  • PPT
  • Word
  • TXT
  • XML
  • You can always see other exporting related articles here.

  • Export Hierarchical (Multi-Level) HTML Table
  • Compress And Export
  • Why

    In my project, we are doing 80% of our work in the client side. So I decided to implement the export feature in the client side itself. The same can be done using server-side code also but I prefer the client-side one.

    What you must know

  • jQuery
  • JavaScript
  • CSS 3
  • HTML
  • DOM Manipulations in jQuery
  • Using the code

    Before you start, you need to download the necessary files from: TableExport.jquery.plugin.

    Once you have download the files, you need to include those in your project. Here I am using a MVC4 web application.

    <script src=“~/Contents/jquery-1.9.1.js”></script>
    <script src=“~/Contents/tableExport.js”></script> @*Main file which does export feature *@
    <script src=“~/Contents/jquery.base64.js”></script> @*Main file which does convert the content to base64  *@
    <script src=“~/Contents/html2canvas.js”></script> @*Main file which does export to image feature *@
    <script src=“~/Contents/jspdf/libs/base64.js”></script> @*Main file which does  convert the content to base64 for pdf *@
    <script src=“~/Contents/jspdf/libs/sprintf.js”></script> @*Main file which does export feature for pdf *@
    <script src=“~/Contents/jspdf/jspdf.js”></script> @*Main file which does export feature for pdf *@

    Let’s say you have an HTML table as follows:

    <table id=“activity” >
                <th>Activity on Code Project (%)</th>
                <th>Activity on C# Corner (%)</th>
                <th>Activity on Asp Forum (%)</th>

    Add some more UI elements for firing the click events.

        <tr id=“footerExport”>
            <td id=“exportexcel”><img src=“~/icons/xls.png” title=“Export to Excel” /></td>
            <td id=“exportpdf”><img src=“~/icons/pdf.png” title=“Export to PDF” /></td>
            <td id=“exportimage”><img src=“~/icons/png.png” title=“Export to PNG” /></td>
            <td id=“exportcsv”><img src=“~/icons/csv.png” title=“Export to CSV” /></td>
            <td id=“exportword”><img src=“~/icons/word.png” title=“Export to Word” /></td>
            <td id=“exporttxt”><img src=“~/icons/txt.png” title=“Export to TXT” /></td>
            <td id=“exportxml”><img src=“~/icons/xml.png” title=“Export to XML” /></td>
            <td id=“exportppt”><img src=“~/icons/ppt.png” title=“Export to PPT” /></td>

    Add a few styles to the table to make it viewable.

        #activity {
            text-align:center;border:1px solid #ccc;
        #activity td{
            text-align:center;border:1px solid #ccc;
         #footerExport td{
           text-align:center;border:1px solid #ccc;

    Now it is time to fire our events 🙂 You can do that as in the following.

        $(document).ready(function () {
            $(‘#exportexcel’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘excel’, escape: ‘false’ });
            $(‘#exportpdf’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘pdf’, escape: ‘false’ });
            $(‘#exportimage’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘png’, escape: ‘false’ });
            $(‘#exportcsv’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘csv’, escape: ‘false’ });
            $(‘#exportppt’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘powerpoint’, escape: ‘false’ });
            $(‘#exportxml’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘xml’, escape: ‘false’ });
            $(‘#exportword’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘doc’, escape: ‘false’ });
            $(‘#exporttxt’).bind(‘click’, function (e) {
                $(‘#activity’).tableExport({ type: ‘txt’, escape: ‘false’ });

    Please note that you can export to a few more formats in the same way. You can learn more here:tableExport.jquery.plugin.


    Now its time go deeper into that plugin. In the downloaded files you can see a file called tableExport.js. just open that file, you can see some conditions for specific formats. And the default property for exporting as follows.

    var defaults = {
                       separator: ‘,’,
                       ignoreColumn: [],

    You can change these properties depending on your needs as follows.

    var varpdfFontSize= ‘7’;
    $(‘#activity’).tableExport({ type: ‘excel’, escape: ‘false’,pdfFontSize:varpdfFontSize});

    You can try all the properties listed above like this :).

    Now in that file you can see an if else if condition that is satisfied for multiple formats. Let me explain for Excel formatting alone.

    var excel=“<table>”;
                        // Header
                        $(el).find(‘thead’).find(‘tr’).each(function() {
                            excel += “<tr>”;
                            $(this).filter(‘:visible’).find(‘th’).each(function(index,data) {
                                if ($(this).css(‘display’) != ‘none’){
                                    if(defaults.ignoreColumn.indexOf(index) == -1){
                                        excel += “<td>” + parseString($(this))+ “</td>”;
                            excel += ‘</tr>’;
                        // Row Vs Column
                        var rowCount=1;
                        $(el).find(‘tbody’).find(‘tr’).each(function() {
                            excel += “<tr>”;
                            var colCount=0;
                            $(this).filter(‘:visible’).find(‘td’).each(function(index,data) {
                                if ($(this).css(‘display’) != ‘none’){
                                    if(defaults.ignoreColumn.indexOf(index) == -1){
                                        excel += “<td>”+parseString($(this))+“</td>”;
                            excel += ‘</tr>’;
                        excel += ‘</table>’
                        if(defaults.consoleLog == ‘true’){
                        var excelFile = “<html xmlns:o=’urn:schemas-microsoft-com:office:office’ xmlns:x=’urn:schemas-microsoft-com:office:”+defaults.type+“‘ xmlns=’′>”;
                        excelFile += “<head>”;
                        excelFile += “<!–[if gte mso 9]>”;
                        excelFile += “<xml>”;
                        excelFile += “<x:ExcelWorkbook>”;
                        excelFile += “<x:ExcelWorksheets>”;
                        excelFile += “<x:ExcelWorksheet>”;
                        excelFile += “<x:Name>”;
                        excelFile += “{worksheet}”;
                        excelFile += “</x:Name>”;
                        excelFile += “<x:WorksheetOptions>”;
                        excelFile += “<x:DisplayGridlines/>”;
                        excelFile += “</x:WorksheetOptions>”;
                        excelFile += “</x:ExcelWorksheet>”;
                        excelFile += “</x:ExcelWorksheets>”;
                        excelFile += “</x:ExcelWorkbook>”;
                        excelFile += “</xml>”;
                        excelFile += “<![endif]–>”;
                        excelFile += “</head>”;
                        excelFile += “<body>”;
                        excelFile += excel;
                        excelFile += “</body>”;
                        excelFile += “</html>”;
                        var base64data = “base64,” + $.base64.encode(excelFile);
              ‘data:application/‘+defaults.type+‘;filename=exportData.doc;’ + base64data);


    Find the UI element (in this case it is our HTML table).

    Loop through the rows of the thread for the header information.

    Apply a filter to avoid the UI elements that has a display as none (filter(‘:visible’)).

    If the UI is visible, append it to the variable (excel += “” + parseString($(this))+ “

    ”;)The same procedure is done for the row vs column values also. The only difference is, here we are looping through the tbody instead of thread.

    After the data is manipulated, data is formulated in the Excel format.
    You can learn more in the attachment.


    Export From HTML Table

    Export From HTML Table

    Points of Interest

    JQuesry, CSS, HTML, Export


    1st version: 18-11-2014
    2nd Version : 24-11-2014

    Changes done

    Added Images to UI elements
    Added some export feature


    Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Your turn. What do you think?

    A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

    Kindest Regards
    Sibeesh Venu

    • Tushar Bhamare


      I tried above code to export html to word, but it didn’t work for me..

      • Can you please provide me some more information?Are you getting any errors? Please check in your browser console.

    • Ali bin Younas

      worked for me 🙂

      • Thanks a lot for your feedback. I am glad it worked for you 🙂

    • Bhoomi Akhani

      Not working for me.. 🙁 It’s not calling the method even on click of export button

      • Can you please check in your browser console whether you are getting any error? I believe your jquery reference is not loaded correctly. Please check.

      • Can you please check whether are you getting any errors in console? Please make sure that you loaded the Jquery reference correctly.

    • scvinod

      Hi, This is not working in IE9. I’m getting this error: Object doesn’t support property or method ‘btoa’. Do you have any workaround?

      • Sorry for the late reply. Right now I don’t have any work around. I will check it and let you know.

    • Kishore Babu

      Hi Sibeesh, Its working for me. But i want to export table hidden columns HTML content also.. Can u help me on this.

      • Yes sure. In tableExport.js file. Please remove the visible condition. It will take hidden td’s also then.

        .filter(‘:visible’) remove this from each statement. I hope it helps.

    • Vikram

      Will this work for table with tree structure ?

      • Yes, I think, since you use normal html control like span and all. It will just export the table with the style you have given. It would be great if you could try and share the result. Thanks in advance.

    • Saurabh Ambekar

      Hi Sibeesh,
      Its not woking on the dynamic data which is getting populated in the table. Its only exporting the static headers. Please help.

      • If it is static, you can bind that data to a container like $(‘#yourid’).html(your data).hide(); Then it will work I guess. Please check once.

        • Saurabh Ambekar

          Ok great. It worked. Thanks a lot.

          • Fantastic. I am glad it worked for you. Thanks for your confirmation.

    • Prashant D

      I have done export as pdf. but only first 3 columns displayed in pdf file. rest 10 columns are not displaying.. 🙁

      • Can you please check the display property of those 10 columns are not none? Please verify it once again and check.

        • Prashant D

          No sibeesh, that is not none. i will send i screenshot. please have a look.
          please look in the screenshot, i had marked it as black box.. the data of a column is cropped and other columns are not present in pdf file.

        • Prashant D

          Sibeesh, Please reply on my issue. its very urgent !

          • Sorry for my late reply. I suggest you to debug in the file tableExport.js. In that file you can find the if condition for pdf, please put a break point and check why those columns are not adding.

            • Prashant D

              Hello Sibeesh, as per my testing, from the tableExport.js each columns are added into the table, but there is something wrong with jspdf.js. it will not populate the large width table into A4 size portrait of pdf and i am not able to understand the code of it.

              • I didn’t test the scenario you mentioned yet. I will test it in this weekend probably. Will let you know then . Thank you

                • Prashant D

                  Sibeesh, I can provide you jsFiddle example, if you want..

                  • Yes please share it here then. Thank you

                    • Prashant D

                      I had created a fiddle for you..

                      if you download table as excel it works perfect.
                      if you export as pdf then file doesn’t show up in new tab. if you save that new tab then it saves the data as pdf file.. and that is not proper as i described earlier.

                      • I tried debugging. The data and all is taking. Even the loop count is correct. It seems there is some issue while passing datauri. Will check and let you know. Thank you

                      • Prashant D

                        Hi Sibeesh, I also had checked everything that you said and that everything is correct. but still it’s not populating the pdf ‘A4’ size file. so might be the issue in jsPdf.js
                        please provide the resolution asap..

                      • Will try buddy.

                      • Prashant D

                        Hello Sibeesh, any update ? found anything ?

    • shajeer Marakkar

      Hi Sibeesh, I have done exporting my table as excel. Everything works well but the colspan and rowspan given to the cells are not with the excel generated. Is there any option to display colspan and rowspan?

      • I suggest you to debug in the file tableExport.js. I guess there you can do that stuffs in excel condition .

        • shajeer Marakkar

          Tanks for the reply. I solved my problem, here is my code
          $(this).filter(‘:visible’).find(‘th’).each(function(index,data) {
          if ($(this).css(‘display’) != ‘none’){
          if(defaults.ignoreColumn.indexOf(index) == -1){
          colSpan = ($(this).prop(“colSpan”) > 0) ? $(this).prop(“colSpan”) : 1;
          rowSpan = ($(this).prop(“rowSpan”) > 0) ? $(this).prop(“rowSpan”) : 1;
          excel += “” + parseString($(this))+ “”;

          • That’s fantastic. Glad you could solve it. And thanks for sharing the information. Much appreciated.

    • rk_it79

      can we provide border in pdf data

      • Yes we can. You can style the tds in tableExport.js file. Please check ☑

        • rk_it79

          i am new to this.can you give some reference,please

          • Please see shajeer Marakkar’s comments here. I suggest you to do the same.

    • gg_07

      I trying to export html table in html.. file export successfully but not open in MS powerpoint. Please help me to solve this issue

      • Thanks for your feedback. Sorry for my late reply. Are you getting any errors in your browser console?

      • Are you getting any errors in browser console?

    • manish kumar

      can we have an option that when click to export pdf button then allow user to save anywhere he/she wants to save the file. Means save as option.

      • manish kumar

        please help

        • manish kumar

          any one there??????

          • manish kumar

            any one there??????

      • Sorry for my late reply. Do you mean any pop up as it usually asks for where to save the files?

    • Dhruvit Patel

      i want to export html table in excel on separate sheets of excel by different departments any one know how to do that

      • Dhruvit Patel

        here this is my code to export in excel

        var tableToExcel = (function () {

        var uri = ‘data:application/;base64,’

        , template = ‘Attendance{table}’

        , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }

        , format = function (s, c) { return s.replace(/{(w+)}/g, function (m, p) { return c[p]; }) }

        return function (table, name) {

        if (!table.nodeType) table = document.getElementById(table)

        var ctx = { worksheet: ‘Attendance’ || ‘Worksheet’, table: table.innerHTML }

        var date1 = $(“#ctl00_ContentPlaceHolder1_txtFromDate”).val();

        var date2 = $(“#ctl00_ContentPlaceHolder1_txtToDate”).val();

        ////window.location.href = uri + base64(format(template, ctx))

        var link = document.createElement(“a”); = date1 + “_To_” + date2 + “.xls”;

        link.href = uri + base64(format(template, ctx));;



    • sakshi mudaliar

      Hi sibeesh ,

      sakshi here actually to be frank m not that good with JQuery can u tell me that how to integrate your code exacly in my code as my data comes from xampp database need to export that selected data to excel format , i have already included file named tableExport.js and tried to call it using <input type="submit" value="Generate Report" but it is not even calling the function and not even giving any error so can u plz help me out on this its urgent so plz respond ASAP i have to submit within 2 weeks plz try to respond ASAP.

      • Hi, can you please try to implement a try catch while calling the function and check you get any error in browser console?Please check whether all the needed references are loaded correctly?And also please make sure that you load JQuery and JQuery ui on top of any other files. Thanks

    • Krina Joshi

      HI ,
      I am getting following error:
      Uncaught TypeError: $(…).tableExport is not a function(anonymous function) x.event.dispatch

      Can you please help!!

      • Hi, can you please check whether all the needed references are loaded correctly?and also please make sure that you load JQuery and JQuery ui on top of any other files. Thanks

    • abinesh

      Hey sabeesh , Abinesh here….. i’ve tried with similar one myselft…. while using command to open excel file…. Excel is prompting with error … Is there any method to solve this error… Thanks in advance!!!

      • Can you please provide me some more information? Please check in your browser console and paste the error you got there.

        • abinesh

          Here’s the prompt in EXCEL… it can render the HTML but shownig the prompt ….. I just wanted this warning to not to be displayed.

    • vijayaraj

      Hi! am having 10 columns and i will export it as pdf then only 4 columns are displaying in the pdf file.i need to display all column ,plz help me….

      • I recommend you to debug through the function. There is a check condition that checks for display none, make sure that all of the columns are visible.

        • vijayaraj

          sorry,that issue can’t resolve plz help and explain briefly what change i do

      • Sp Ganesh

        hey @disqus_qIzRZtUfXy:disqus .. In tableExport.js file locate at pdf section and change the code below row/column section
        ” var colPosition=startColPosition+(index*50); ”
        “var colPosition=startColPosition+(index*10);”

        this may help for 10 columns….. or even try various numbers to be multiplied with the index value to get all the columns of a table in clear format..

        • That’s a good piece of information, thanks much ☺. This will help some people.

          • Sp Ganesh

            Ya yes sure 🙂

          • Sp Ganesh

            I have a html table. And while exporting it to pdf i get only the table headings and table data. Is there any code to print the table border in pdf.. Or we should write any code in tableExport.js to print the table border? if so suggest me some ideas.

            • Hey hi, in the tableExport.js there is a loop which actually looping though the th’s and td’s available. There you can get the CSS and apply when we create dynamic td’s and th’s. Please check that file. Hope this helps. It would be great if you can share the code or steps here once after you did the requirement. Thank you.

              • Sp Ganesh

                hey hi.. i couldn’t get the desired output.. can you help me out?
                i just need a table border in pdf

    • vijayaraj

      anyone there?

    • vijayaraj

      plz answer my qns

    • vijayaraj

      Hi! i am having 15 columns if i ignore column 12 and 13 its ignoring bit also ignoring column 1,2 and 3 also,so pls tell how to solve that

    • Desarollo3 Cnet

      Hello, my problem is I have to show 13 columns and not as samples all, I think that can be the size of the columns and the space between them but not change either the spaces between columns or something, as I show in letter image is very small, I know how to make it bigger, but not how to make me leave the entire table since many columns and do not fit that way

    Footer With Address And Phones