使用sheetJS在单个工作表中包含多个表

时间:2018-08-13 20:12:06

标签: javascript html excel sheetjs

我成功使用了example from sheetJS's website,就像这样:

/* 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 */

是否可以将多个html表附加到一张纸上?它们具有相同的结构。我想可能是这样,

/* 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");

1 个答案:

答案 0 :(得分:4)

我从以下链接中找到了答案: https://codepen.io/anon/pen/EebyzQ?editors=0010

它的作用是将工作表合并为一个,跳过第一个的标题,然后将其导出为 Excel 表:

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')
}