-1

I am trying to export a table in a jsp page to excel sheet using a button. The button on clicking should give a dialogue box to save or cancel. I need the code using java or javascript.

niz
  • 33
  • 5
  • StackOverflow is for solving coding problems. It's not your personal coding machine. – Ashiqur Rahman Jul 26 '17 at 10:29
  • 1
    Possible duplicate of [Export HTML table to excel - using jQuery or Java](https://stackoverflow.com/questions/3206775/export-html-table-to-excel-using-jquery-or-java) – Ashiqur Rahman Jul 26 '17 at 10:31

1 Answers1

1

Excel export script works on IE7+, Firefox and Chrome

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Just create a blank iframe:

<iframe id="txtArea1" style="display:none"></iframe>

Call this function on:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
Feras Al Sous
  • 1,073
  • 1
  • 12
  • 23
  • It worked. Thanks. I am getting a pop up for save as. I would like to modify to get a file download pop up. – niz Jul 26 '17 at 11:12