Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I try to export html table to excel using javascript. The I got this pop up before open the excel file:
if you try open test.xls, is in different format than specified by the extension file

What I have tried:

This is my code:
var tableToExcel = (function () {
    var uri = 'data:application/;base64,'
          , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
            'xmlns=""><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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head> ' +
            , 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, filename) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }      
        var a = document.createElement('a');
        a.href = uri + base64(format(template, ctx)); = filename + '.xls';;
Updated 6-Sep-17 23:09pm

1 solution

Share this answer
Andy07 7-Sep-17 23:33pm    
I use html table, what is How to Export GridView To Word/Excel/PDF/CSV in ASP.Net | The ASP.NET Forums[^] can solve that problem too?
Graeme_Grant 7-Sep-17 23:38pm    
GridView generates a html table. So it will take very little to adapt to your needs. It is called programming.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900