I am successfully using the example from sheetJS's website, like so:
/* create new workbook */
var workbook = XLSX.utils.book_new();
/* convert table 'table1' to worksheet named "Sheet1" */
var ws1 = XLSX.utils.table_to_sheet(document.getElementById('table1'));
XLSX.utils.book_append_sheet(workbook, ws1, "Sheet1");
/* convert table 'table2' to worksheet named "Sheet2" */
var ws2 = XLSX.utils.table_to_sheet(document.getElementById('table2'));
XLSX.utils.book_append_sheet(workbook, ws2, "Sheet2");
/* workbook now has 2 worksheets */
Is it possible to append multiple html tables to a single sheet? They have the same structure. I imagine it could be something, like so:
/* convert 'table1', 'table2', 'table3' to single sheet named "Sheet1" */
var ws1 = XLSX.utils.table_to_sheet(document.getElementById('table1'));
var ws2 = XLSX.utils.table_to_sheet(document.getElementById('table2'));
var ws3 = XLSX.utils.table_to_sheet(document.getElementById('table3'));
XLSX.utils.book_append_sheet(workbook, {ws1, ws2, ws3}, "Sheet1");
I found the answer from this following link: https://codepen.io/anon/pen/EebyzQ?editors=0010
What it does is it appends the worksheets into one, skips the header of the first one, and then exports it as an excel sheet:
function convert(){
let tbl1 = document.getElementsByTagName("table")[0]
let tbl2 = document.getElementsByTagName("table")[1]
let worksheet_tmp1 = XLSX.utils.table_to_sheet(tbl1);
let worksheet_tmp2 = XLSX.utils.table_to_sheet(tbl2);
let a = XLSX.utils.sheet_to_json(worksheet_tmp1, { header: 1 })
let b = XLSX.utils.sheet_to_json(worksheet_tmp2, { header: 1 })
a = a.concat(['']).concat(b)
let worksheet = XLSX.utils.json_to_sheet(a, { skipHeader: true })
const new_workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(new_workbook, worksheet, "worksheet")
XLSX.writeFile(new_workbook, 'tmp_file.xls')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With