` (含跨行跨列 `rowspan`/`colspan`) 精確轉換為 Excel 檔案。僅限 IE/舊版 Edge (IE 模式) 及已安裝 Excel 的 Windows 環境,現代瀏覽器不支援 ActiveX。
核心 JS 元件:TableToExcel.js
/**
* HTML Table 轉 Excel 通用元件
* 支援:合併儲存格 (rowspan/colspan)、樣式設定、自適應寬度
* 依賴:客戶端需安裝 Microsoft Excel、IE/Edge IE模式、ActiveX 啟用
*/
function TableToExcel(tableID) {
this.tableBorder = -1; // 邊框: -1無, 1-4 不同樣式
this.backGround = 0; // 背景色 (調色盤索引)
this.fontColor = 1; // 字體色
this.fontSize = 10; // 字體大小
this.fontStyle = '微軟雅黑'; // 字體
this.rowHeight = -1; // 行高
this.columnWidth = -1; // 列寬 (-1 自動)
this.lineWrap = true; // 自動換行
this.textAlign = -4108; // 對齊: -4108置中, -4131靠左, -4152靠右
this.autoFit = false; // 自適應列寬
this.tableID = tableID;
}
// 設定方法鏈
['TableBorder','BackGround','FontColor','FontSize','FontStyle','RowHeight',
'ColumnWidth','LineWrap','TextAlign','AutoFit'].forEach(prop => {
TableToExcel.prototype['set' + prop] = function(val) {
this[prop.charAt(0).toLowerCase() + prop.slice(1)] = val;
return this;
};
});
// 核心導出邏輯
TableToExcel.prototype.getExcelFile = function() {
let excel, workbook, sheet, htmlTable;
try {
excel = new ActiveXObject('Excel.Application');
} catch (e) {
alert('無法啟動 Excel!\n請確認:\n1. 已安裝 Excel\n2. IE 設定:工具→Internet選項→安全→自定義級別→ActiveX控件→啟用「對未標記為安全的ActiveX控件初始化和腳本運行」');
return false;
}
excel.Visible = true;
workbook = excel.Workbooks.Add();
excel.DisplayAlerts = false;
workbook.Worksheets(3).Delete(); // 只保留 1 個工作表
workbook.Worksheets(2).Delete();
excel.DisplayAlerts = true;
sheet = workbook.ActiveSheet;
// 1. 計算實際行列數 (處理合併儲存格)
htmlTable = document.all.tags('table').item(
[...document.all.tags('table')].findIndex(t => t.id === this.tableID)
);
if (!htmlTable) return alert('找不到 Table: ' + this.tableID);
const totalRows = htmlTable.rows.length;
let totalCols = 0;
for (let i = 0; i < htmlTable.rows[0].cells.length; i++) {
totalCols += htmlTable.rows[0].cells[i].colSpan || 1;
}
// 2. 建立佔位矩陣 標記已佔用儲存格
const occupied = Array.from({length: totalRows + 1}, () => Array(totalCols + 1).fill(false));
// 3. 設定全域樣式
if (this.columnWidth > 0) sheet.Columns.ColumnWidth = this.columnWidth;
if (this.rowHeight > 0) sheet.Rows.RowHeight = this.rowHeight;
// 4. 遍歷 HTML Table 寫入 Excel
for (let r = 0; r < totalRows; r++) {
let excelRow = r + 1; // Excel 1-based
let excelCol = 1;
const htmlRow = htmlTable.rows[r];
for (let c = 0; c < htmlRow.cells.length; c++) {
const cell = htmlRow.cells[c];
// 找下一個未佔用的列
while (occupied[excelRow][excelCol]) excelCol++;
const colSpan = cell.colSpan || 1;
const rowSpan = cell.rowSpan || 1;
// 標記佔用
for (let dr = 0; dr < rowSpan; dr++) {
for (let dc = 0; dc < colSpan; dc++) {
occupied[excelRow + dr][excelCol + dc] = true;
}
}
// 寫入值
const cellValue = cell.innerText || cell.textContent || '';
const excelCell = sheet.Cells(excelRow, excelCol);
excelCell.Value = cellValue;
// 合併儲存格
if (colSpan > 1 || rowSpan > 1) {
const endCell = sheet.Cells(excelRow + rowSpan - 1, excelCol + colSpan - 1);
sheet.Range(excelCell, endCell).Merge();
}
// 樣式
if (this.tableBorder > 0) {
const range = (colSpan > 1 || rowSpan > 1) ?
sheet.Range(excelCell, endCell) : excelCell;
range.Borders.LineStyle = this.tableBorder;
}
if (this.fontStyle) excelCell.Font.Name = this.fontStyle;
if (this.fontSize) excelCell.Font.Size = this.fontSize;
if (this.fontColor) excelCell.Font.ColorIndex = this.fontColor;
if (this.backGround) excelCell.Interior.ColorIndex = this.backGround;
if (this.lineWrap) excelCell.WrapText = true;
excelCell.HorizontalAlignment = this.textAlign;
excelCol += colSpan;
}
}
// 5. 自適應列寬
if (this.autoFit) sheet.Columns.AutoFit();
return true;
};
簡化入口函數
function saveAsExcel(tableID) {
const tb = new TableToExcel(tableID);
tb.setFontStyle('微軟雅黑')
.setFontSize(10)
.setTableBorder(2)
.setColumnWidth(12)
.setLineWrap(true)
.setAutoFit(true)
.getExcelFile();
}
HTML 表格範例 (含多級表頭)
<table id="reportTable" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr style="background:#4472C4;color:white;">
<th rowspan="2">部門</th>
<th colspan="3">2024 年度業績</th>
<th rowspan="2">備註</th>
</tr>
<tr style="background:#5B9BD5;color:white;">
<th>Q1</th><th>Q2</th><th>Q3</th>
</tr>
</thead>
<tbody>
<tr><td>業務部</td><td>1200</td><td>1350</td><td>1400</td><td>增長中</td></tr>
<tr><td>技術部</td><td>800</td><td>950</td><td>1100</td><td>招聘中</td></tr>
</tbody>
</table>
<button onclick="saveAsExcel('reportTable')">導出 Excel</button>
關鍵技術點解析
1. 合併儲存格處理算法
- 建立二維布林陣列 `occupied[row][col]` 標記 Excel 儲存格是否已被上一列/行合併佔用
- 遍歷 HTML `
| `/` | `,讀取 `colSpan`、`rowSpan` 屬性
- 在 `occupied` 中標記對應區域為 `true`
- 寫入值時跳過已佔用欄位,確保數據對齊
- 呼叫 `Range.Merge()` 合併 Excel 儲存格
2. 樣式映射
| HTML/CSS | Excel COM 屬性 |
| border | Range.Borders.LineStyle (1=細實線, 2=中實線, 3=虛線, 4=點線) |
| background-color | Interior.ColorIndex (調色盤索引 1-56) 或 Color (RGB) |
| color | Font.ColorIndex |
| font-family | Font.Name |
| font-size | Font.Size |
| text-align | HorizontalAlignment (-4108置中, -4131左, -4152右) |
| white-space:nowrap | WrapText = false |
現代替代方案 (跨瀏覽器、無 ActiveX)
1. SheetJS (xlsx.js) - 純前端、最推薦
<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
<button onclick="exportXLSX()">導出 XLSX</button>
<script>
function exportXLSX() {
const table = document.getElementById('reportTable');
const wb = XLSX.utils.table_to_book(table, {sheet: "報表", raw: true});
// 處理合併儲存格 (需手動設定 !merges)
const merges = [];
// ... 解析 table 結構計算 merges ...
wb.Sheets['報表']['!merges'] = merges;
XLSX.writeFile(wb, '報表.xlsx');
}
</script>
2. ExcelJS (Node.js/瀏覽器、支援樣式、流式寫入)
// 前端用法 (需打包)
import ExcelJS from 'exceljs';
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('報表');
// 逐行寫入、設定樣式、合併儲存格
await workbook.xlsx.writeBuffer().then(buf => saveAs(buf, '報表.xlsx'));
3. 後端生成 (Apache POI / Spring Boot)
@GetMapping("/export")
public void export(HttpServletResponse resp) throws IOException {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("報表");
// 寫入標題、合併儲存格 sheet.addMergedRegion(new CellRangeAddress(0,1,0,0))
// 設定 CellStyle (字體、邊框、顏色、對齊)
resp.setHeader("Content-Disposition", "attachment;filename=report.xlsx");
wb.write(resp.getOutputStream());
}
方案選型建議
| 方案 | 優點 | 缺點 | 適用場景 |
| ActiveX TableToExcel | 完美還原合併儲存格、可直接操作 Excel 應用程式 | 僅 IE/Win、需安裝 Excel、安全風險、已淘汰 | 內網舊系統、IE 強制環境 |
| SheetJS (xlsx.js) | 純前端、跨平台、無依賴、開源免費 | 合併儲存格需手動處理、大檔案效能一般 | 現代 Web 專案首選 |
| ExcelJS | 豐富樣式支援、流式寫入大檔案 | 體積較大、API 複雜 | 需精細控制樣式、大數據導出 |
| 後端 POI | 完全可控、無前端限制、支援複雜報表 | 佔用伺服器資源、需下載檔案 | 企業級報表、定時任務、權限控制 |
總結
TableToActiveX 方案是早期內網系統的經典選擇,完美解決 HTML Table 合併儲存格導出難題。但隨著 IE 退役、ActiveX 淘汰,**強烈建議遷移至 SheetJS 或後端 POI 方案**。現代架構下,前端負責觸發導出、後端生成檔案流返回,或純前端 SheetJS 處理中小數據量導出,更安全、跨平台、可維護。
copyright © 萬盛學電腦網 all rights reserved
|