<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
?
<div id="printA">
<!-- 表格1 -->
<table>
<tr><th>姓名</th><th>部門(mén)</th></tr>
<tr><td>張三</td><td>技術(shù)部</td></tr>
</table>
<!-- 表格2 -->
<table>
<tr><th>項(xiàng)目</th><th>進(jìn)度</th></tr>
<tr><td>系統(tǒng)升級(jí)</td><td>50%</td></tr>
<tr><td>安全審計(jì)</td><td>已完成</td></tr>
</table>
</div>
<button onclick="exportAllToOneSheet()">合并導(dǎo)出</button>
<script>
function exportAllToOneSheet() {
const div = document.getElementById('printA');
const tables = div.getElementsByTagName('table');
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([[]]); // 創(chuàng)建空工作表
let currentRow = 0; // 當(dāng)前寫(xiě)入行指針
Array.from(tables).forEach((table, tableIndex) => {
// 將表格轉(zhuǎn)換為二維數(shù)組
const tableData = XLSX.utils.sheet_to_json(
XLSX.utils.table_to_sheet(table),
{ header: 1 }
);
// 添加表格間的分隔空行(第一個(gè)表格前不加)
if (tableIndex > 0) {
XLSX.utils.sheet_add_aoa(ws, [[""]], { origin: { r: currentRow, c: 0 } });
currentRow++;
}
// 將表格數(shù)據(jù)寫(xiě)入工作表
XLSX.utils.sheet_add_aoa(ws, tableData, {
origin: { r: currentRow, c: 0 } // 從當(dāng)前行開(kāi)始寫(xiě)入
});
// 更新行指針(+數(shù)據(jù)行數(shù))
currentRow += tableData.length;
});
// 將工作表添加到工作簿
XLSX.utils.book_append_sheet(wb, ws, "合并數(shù)據(jù)");
// 生成并下載文件
XLSX.writeFile(wb, 'combined_tables.xlsx');
}
</script>