How can I convert multiple html tables to an excel sheet with multiple worksheets? Could you please help into this.
My example https://jsfiddle.net/kdkd/5p22gdag/
Use Below code for multiple sheets. I am using three tables data for generating excel. Import library:
import * as XLSX from "xlsx";
static doExcel1(tableId1, tableId2, tableId3) {
let targetTableElm1 = document.getElementById(tableId1);
let targetTableElm2 = document.getElementById(tableId2);
let targetTableElm3 = document.getElementById(tableId3);
const wb = { SheetNames: [], Sheets: {} };
var ws1 = XLSX.utils.table_to_book(targetTableElm1).Sheets.Sheet1;
wb.SheetNames.push("Sheet1"); wb.Sheets["Sheet1"] = ws1;
var ws2 = XLSX.utils.table_to_book(targetTableElm2).Sheets.Sheet1;
wb.SheetNames.push("Sheet2"); wb.Sheets["Sheet2"] = ws2;
var ws3 = XLSX.utils.table_to_book(targetTableElm3).Sheets.Sheet1;
wb.SheetNames.push("Sheet3"); wb.Sheets["Sheet3"] = ws3;
console.log(ws1); console.log(ws2); console.log(ws3); console.log(wb);
const blob = new Blob([this.s2ab(XLSX.write(wb, { bookType: 'xlsx', type: 'binary' }))], {
type: "application/octet-stream"
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'demo.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
static s2ab(s) {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
Call using table ids: doExcel1("ExampleTable1","ExampleTable2","ExampleTable3"); on click of button.
NOTE: Above solution is only for angular if you want use it in node or js then you need to some changes.
@Butani Vijay
I found one issue with your code. Though maybe you could argue maybe my source table is not strictly HTML compliant.
Specifically my table is defined similar to
<table id="tbl1">
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Last<br>Login</th>
<th>Suspended</th>
</tr>
</thead>
<tbody>
<tr>
<td><a target="_new" href="https://xxxxx.zendesk.com/agent/users/378955944453">Joe User</a></td>
<td>JUser@xyz.edu</td>
<td>2020-02-18T16:42:50Z</td>
<td>false</td>
</tr>
<tfoot>
<tr>
<td><b>Totals: </b></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
</tbody>
</table>
and because of the <br>
included in <th>Last<br>Login</th>
the XML parse indicates it expected a </br>
. But why ??? HTML doesnt really have a </br>
And because of this although XLS would open there was no data in the spreadsheet, nor were any worksheets defined
But a suitable fix is to change in your javascript of
dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
to
dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerText;