jureispro
jureispro

Reputation: 1402

Failing to load data into excel file when exporting HTML table to Excel

I want to export HTML table to excel file. Problem is that data inside table are not exporting. Table headers are successfully exported but data is not.Also I have problem with encoding. Some special characters are not displaying correctly. Does someone knows where's the problem?

Here is my code:

HTML TABLE:

<table id"table2excel">
    <tbody>
    <tr>
        <th>First Name</th><th>Last name</th><th>Score</th>
    </tr>
    <tr>
        <td>John</td><td>Doe</td><td>23124</td>
    </tr>
    <tr>
        <td>Jane</td><td>Doe</td><td>35555</td>
    </tr>
    </tbody>
</table>

JavaScript

 <script type="text/javascript">
        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}
            window.location.href = uri + base64(format(template, ctx))
          }
        })()
        </script>

Upvotes: 1

Views: 1021

Answers (1)

Zee
Zee

Reputation: 8488

You have an error in your html and script.

<table id"table2excel">

should be

<table id="table2excel">

I created a fiddle :

http://jsfiddle.net/Sourabh_/5ups6z84/2/

Upvotes: 3

Related Questions