user2731867
user2731867

Reputation: 61

exporting html table to xls not working using jquery

 <script>
 $(document).ready(function(){
 $("#btnExport").click(function(e) {

  window.open('data:application/vnd.ms-excel,' + $('#dvDatatable').html());
  e.preventDefault();
  });
  });
 </script>

This is the code i used to export my html table where #btnExport is my export button and '#dvDatatable' is my table id.But this code is not working for me. Its just downloading like simple file

What changes i have to do in my code?

Upvotes: 0

Views: 1346

Answers (1)

V31
V31

Reputation: 7666

You can make use of this function:

var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
        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: name || 'Worksheet',
                table: table.innerHTML
            }
            var blob = new Blob([format(template, ctx)]);
            var blobURL = window.URL.createObjectURL(blob);
            return blobURL;
        }
})()

And in your jquery something like this:

$("#btnExport").click(function () {
    var blobURL = tableToExcel('account_table', 'test_table');
    $(this).attr('download','download.xls')
    $(this).attr('href',blobURL);
});

Example Fiddle

References: Link1 Link2

Upvotes: 1

Related Questions