Search code examples
javascripthtml-tableexport-to-excel

Exporting HTML table with correct format in Javascript


I have a table and I have there a amount column. I want to export the table with the correct number format because when I do export my table, I only get 100 instead of 100.00.

My table look like this:

ID    Code    Amount    Time
1      1      100.00    2014-09-22 18:59:25
1      1      100.60    2014-09-22 18:59:25
1      1      100.00    2014-09-22 18:59:25
1      1       12.50    2014-09-22 18:59:25

And the Excel output is like this:

ID    Code    Amount    Time
1      1         100    2014-09-22 18:59:25
1      1      100.60    2014-09-22 18:59:25
1      1         100    2014-09-22 18:59:25
1      1        12.5    2014-09-22 18:59:25

This is my code:

    <script>
    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, filename) {
            if (!table.nodeType) table = document.getElementById(table)
            var ctx = {
                worksheet: name || 'Worksheet',
                table: table.innerHTML
            }

            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();

        }
    })()
    function download(){
        $(document).find('tfoot').remove();
        var name = document.getElementById("name").innerHTML;
        tableToExcel('table2', 'Sheet 1', name+'.xls')
        setTimeout("window.location.reload()",0.0000001);

    }
    var btn = document.getElementById("btn");
    btn.addEventListener("click",download);
    </script>

Is there any way to achieve this? I want my Excel file to look exactly like the data in my table.


Solution

  • Try with

    <td style='mso-number-format:"#,##0.00"'>100.00</td>
    

    in the table HTML.

    See fiddle: http://jsfiddle.net/ad3xda1z/1/

    Greetings

    Axel