My table is in format
<table id="mytable">
<thead>
<tr>
<th>name</th>
<th>place</th>
</tr>
</thead>
<tbody>
<tr>
<td>adfas</td>
<td>asdfasf</td>
</tr>
</tbody>
</table>
I found the following code online. But it doesn’t work if i use “thead” and “tbody” tags
function write_to_excel() {
str = "";
var mytable = document.getElementsByTagName("table")[0];
var rowCount = mytable.rows.length;
var colCount = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for (var i = 0; i < rowCount; i++) {
for (var j = 0; j < colCount; j++) {
str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i + 1, j + 1).Value = str;
}
}
The reason the solution you found on the internet is no working is because of the line that starts
var colCount. The variablemytableonly has two elements being<thead>and<tbody>. Thevar colCountline is looking for all the elements withinmytablethat are<tr>. The best thing you can do is give an id to your<thead>and<tbody>and then grab all the values based on that. Say you had<thead id='headers'>:and then do the same thing for the
<tbody>tag.EDIT: I would also highly recommend using jQuery. It would shorten this up to:
Now, of course, this is going to give you some formatting issues but you can work out how you want it formatted in Excel.
EDIT: To answer your question about how to do this for
nnumber of tables, the jQuery will do this already. To do it in raw Javascript, grab all the tables and then alter the function to be able to pass in the table as a parameter. For instance:Then change the
function write_headers_to_excel()tofunction write_headers_to_excel(table). Then changevar myTableHead = document.getElementById('headers');tovar myTableHead = table.getElementsByTagName('thead')[0];. Same with yourwrite_bodies_to_excel()or however you want to set that up.