2

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3771102
  • 558
  • 2
  • 8
  • 27

2 Answers2

9

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

Axel Richter
  • 56,077
  • 6
  • 60
  • 87
  • @Adrian: No because IE does not support `data:` URIs used as a link target. But the whole approach is outdated since there are libraries which really can create `Excel` file formats (`*.xls` or `*.xlsx`). So there is no need to fake `HTML` as `schemas-microsoft-com:office:excel` `XML` anymore. – Axel Richter May 09 '19 at 03:31
0

in excel itself:
by default it is not showing .00 - but you can change it in the formating options

so eventually there is a (xml) option to specify the cell formating. then the formating code would be something like 0.00

found: HTML to Excel: How can tell Excel to treat columns as numbers?
some formating code examples
so you can try to add a style="mso-number-format:0\.00000;" to the cell

other option is to try to force excel to interpret the cell content as text - for this you can try to prefix every cell content with a '

i have build a stack snippet example. the relevant code is:

// deep clone of table
//https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
var temp_table = document.getElementById('table_XXXX').cloneNode(true);
// get all table cells
var table_cells = temp_table.getElementsByTagName('td');
// console.log("table_cells", table_cells);
// modify all table cells
for (var i = 0; i < table_cells.length; i++) { 
    var cell = table_cells[i];
    // console.log("cell", cell);
    // cell.textContent = "'" + cell.textContent;
    cell.setAttribute("style", "mso-number-format:0\.00000;");
}

console.log("temp_table", temp_table);

var tableToExcel = (function () {
 // var uri = 'data:application/vnd.ms-excel;base64,';
 
 var template = '<html lang="en" xml:lang="en" 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><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="DC.language" content="en"><!--[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>';
 
 // var  base64 = function (s) {
  // return window.btoa(unescape(encodeURIComponent(s)))
 // };
 
 var 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
  }
  // return uri + base64(format(template, ctx));
  return format(template, ctx);
 }
})()


function saveAsFile(link, content, mimetype, filename) {
 // https://developer.mozilla.org/en-US/docs/Web/API/Blob
 // var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
 // var oMyBlob = new Blob(aFileParts, {type: 'text/html'}); // the blob
 
 // https://stackoverflow.com/a/16330385/574981
 var blob = new Blob([content], mimetype);
 var url  = URL.createObjectURL(blob);
 
 console.log("update download link:");
 var a = link;
 a.download    = filename;
 a.href        = url;
 // a.textContent = "Download File";
 console.log("download link:", a);
}

function saveAsFile_handleClick(event){
 console.log("saveAsFile_handleClick");
 // deep clone of table
 //https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
 var temp_table = document.getElementById('table_XXXX').cloneNode(true);
 // get all table cells
 var table_cells = temp_table.getElementsByTagName('td');
 // console.log("table_cells", table_cells);
 // modify all table cells
 for (var i = 0; i < table_cells.length; i++) { 
  var cell = table_cells[i];
  // console.log("cell", cell);
  // cell.textContent = "'" + cell.textContent;
  cell.setAttribute("style", "mso-number-format:0\.000;");
 }
 console.log("temp_table", temp_table);
 // function saveAsFile(link, content, mimetype, filename);
 saveAsFile(
  this,
  tableToExcel(temp_table, 'Sheet 1'), 
  {type: "application/msexcel"}, 
  "test.xls"
 );
} 

function initSystem(){
 console.groupCollapsed("system init:");
 
 // save output button
 var saveOutputButton = document.getElementById("saveAsFile");
 if (saveOutputButton) {
  console.log("add click event to '#saveAsFile':");
  saveOutputButton.addEventListener('click', saveAsFile_handleClick, false);
 }
 
 console.log("finished.");
 console.groupEnd();
}

/* * pure JS - newer browsers...* */
document.addEventListener('DOMContentLoaded', initSystem, false);
#btn {
  margin: 1em;
}

tr:hover {
  background-color: rgba(255, 200, 0, 0.5);
  
}

td {
  padding: 0 1.5em;
  text-align: right;
}


a, a:link {
 margin:     0px;
 padding:    0px;
 text-decoration:  none;
 color:     inherit;
 cursor:     pointer;
 display:    inline;
}


a:hover {
 background-color:  rgba(255,190,000,0.5);
 /*box-shadow:   x y color [blur] [spread] [inset]*/
 box-shadow:    0px 0px 5px rgba(255,190,0,0.5), 0px 0px 20px rgba(255,190,0,0.5);
}


.button, a.button:link {
 display:    block;
 width:     20em;
 padding:    0.5em;
 margin:     1em;
 border-radius:   1em;
 background-color:  rgba(0, 0, 0, 0.35);
 box-shadow:    0px 0px 10px rgba(0,0,0,0.2), 0px 0px 10px rgba(255,255,255,0.1) inset;
 cursor:     pointer;
 text-align:    center;
}

.button:hover, a.button:link:hover {
 background-color:  rgba(0, 0, 0, 0.36);
 box-shadow:    1px 1px 10px rgba(0,0,0,0.3), 0px 0px 10px rgba(255,255,255,0.1) inset;
}
<div>
 <a class="button" id="saveAsFile" href="#">
  Save Table to Excel File
 </a>
</div>


<div id="tablecontainer">
 <table id="table_XXXX">
  <tbody>
   <tr>
    <th>ID</th>
    <th>Code</th>
    <th>Amount</th>
    <th>Time</th>
   </tr>
   <tr>
    <td>1</td>
    <td>1</td>
    <td>100.00</td>
    <td>2014-09-19 18:59:25</td>
   </tr>
   <tr>
    <td>1</td>
    <td>1</td>
    <td>100.60</td>
    <td>2014-09-20 18:59:25</td>
   </tr>
   <tr>
    <td>1</td>
    <td>1</td>
    <td>200.00</td>
    <td>2014-09-21 18:59:25</td>
   </tr>
   <tr>
    <td>1</td>
    <td>1</td>
    <td>12.50</td>
    <td>2014-09-22 18:59:25</td>
   </tr>
  </tbody>
 </table>
</div>
Community
  • 1
  • 1
  • But I needed to show the .00 right after I opened the file. It is not me who will open it. It is the client. How will I format it? – user3771102 Sep 23 '14 at 07:30
  • you could try to escape the Amount as Text - for this you would have to modifie the table data so that an ' is in front of the text. but than you can not calculate with this cell content any more. – Stefan Krüger s-light Sep 23 '14 at 07:34
  • What do you mean by text? In my database which is where the data comes from, I have changed its type to varchar so that it would also show 2 decimal point. – user3771102 Sep 23 '14 at 07:37
  • i think you can't specify the format for the cells in this html embedded thing. you generating no real xls file - it is a xls file that has html embeded - so you have not all the options to format the content. my idea was to iterate over the content of your html table and prefix the cell content with a ' - so excel will interpret this content as text. – Stefan Krüger s-light Sep 23 '14 at 07:55