1

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>

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I like that you included a fiddle.
@Zee Hey, this works well but how to modify it if i want the same thing on a button click?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.