Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi Im trying to convert html tables to excel, i have tried with a javascript function which converts a simple table to excel, it is working fine. If I have multiple tables how will I be able to add all the table data into the excel file. here's what I tried. i've created 2 tables and given table index testTable and testTable1. How will i pass these 2 table ids to the javascript function on click of the button. right now on click of the button only the first table is exported to excel as im passing only 'testTable'. how will i be able to export multiple tables eg: testTable, testTable1 into excel.

Here's the 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>

Here's the html part,

<table id="testTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Unix<br>
                NT 3.1</th>
            <th>Unix<br>
                NT 3.51</th>
            <th>Unix<br>
                95</th>
        </tr>
    </thead>
</table>
<table id="testTable1">
    <thead>
        <tr>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Windows<br>
                NT 3.1</th>
            <th>Windows<br>
                NT 3.51</th>
            <th>Windows<br>
                95</th>
        </tr>
    </thead>
</table>

Please let me know, how this can be done Thanks

share|improve this question
Can't you use web service for this problem. It will also work without postback. – sanalism Mar 5 at 12:50

4 Answers

up vote 6 down vote accepted

I recommend another Format method. the John Resig micro-template is a very good and simple tool for do what you need. (ejohn microtemplating)

(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str.replace(/[\r\t\n]/g, " ")
              .split("{{").join("\t")
              .replace(/((^|}})[^\t]*)'/g, "$1\r")
              .replace(/\t=(.*?)}}/g, "',$1,'")
              .split("\t").join("');")
              .split("}}").join("p.push('")
              .split("\r").join("\\'")
              + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

It is very simple to use. This allows not only show variables between HTML but also execute JavaScript code

Your template string need some modification to work with this microtemplate.

{{for(var i=0; i<tables.length;i++){ }}
    <table>
        {{=tables[i]}}
    </table>
{{ } }}

finally only need to select all the tables that appear in your example

document.getElementsByTagName("table");

you can see how it works http://jsfiddle.net/Scipion/P8rpn/1/

share|improve this answer
Thanks a ton Scipion! I just wanted to know if I can do this functionality on click of a html button...I tried with this <input type="button" onclick="tableToExcel(document.getElementsByTagName("table"),"one")" value="Export to Excel"> but this ain't working....How is it working on jsFiddle? If I implement the same in html I'm not able to get the file on click of the button. Kindly let me know if this is possible. – monishchandrashekar Mar 9 at 18:57
try <button id="btn">Download</button> and to add it the click event. function download(){ tableToExcel(document.getElementsByTagName("table"), "one"); } var btn = document.getElementById("btn"); btn.addEventListener("click",download); jsfiddle.net/Scipion/P8rpn/3 – Scipion Mar 11 at 11:09
Thanks a lot!! This worked like a charm! :) – monishchandrashekar Mar 12 at 18:04
hey, the file is getting downloaded as 'download.xls'; how can I change the name of the download file? – monishchandrashekar Apr 8 at 6:12
In chrome is the default name. For use another name you can use a third party solution stackoverflow.com/questions/13912198/… – Scipion Apr 10 at 10:29

create a function and pass the tableID to it

 function passing_id_to_excel(tableID){ 
  var myTableid =
 document.getElementById(tableID) //remaining code }
share|improve this answer
How will I pass multiple tableIDs? – monishchandrashekar Mar 5 at 13:50
  1. Add a checkbox for each table. Use javascript to process those that are checked.
  2. In case if you just want to convert every table, you could use $('table').each(function() { do something }).
share|improve this answer

Just create a csv file.

When you open the exel or libre office, it displays the data as have recorded, is much easier to use xml or html.

//myfile.csv

titulo1, titulo2, titulo3
dato11, dato12, dato13
dato21, dato22, dato23

csv_to_excel | excel_info

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.