2024-01-01 08:29:58
使用 Exceljs 和 x-spreadsheet 库固定表头,核心是通过配置 view 对象中的 fixedRowHeight 属性实现。以下是具体实现步骤和代码示例:
1. x-spreadsheet 固定表头x-spreadsheet 是一个基于浏览器的表格库,通过配置 view 参数可固定表头,关键属性如下:
示例代码:
const options = { view: { // 固定表头高度为25像素 fixedRowHeight: 25, // 动态计算表格主体高度(视口高度 - 表头高度 - 其他预留空间) height: () => { return document.documentElement.clientHeight - 40; // 40为预留空间(如工具栏) }, // 其他视图配置(如列宽、滚动条等) showToolbar: true, showGrid: true }};// 初始化表格const spreadsheet = new XSpreadsheet('#container', options);关键点:
Exceljs 是一个服务端或Node.js环境的Excel文件操作库,本身不支持前端表格渲染,因此无法直接实现表头固定功能。若需在Excel文件中模拟固定表头效果,可通过以下方式间接实现:
若需在前端展示并导出固定表头的表格,可分两步实现:
示例代码:
// 1. 前端渲染(x-spreadsheet)const spreadsheet = new XSpreadsheet('#container', { view: { fixedRowHeight: 25, height: () => window.innerHeight - 100 }});// 2. 导出Excel(Exceljs)function exportToExcel() { const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Sheet1'); // 填充数据(从x-spreadsheet获取) const data = spreadsheet.getData(); // 假设存在此方法 data.forEach(row => { worksheet.addRow(row); }); // 冻结首行 worksheet.views = [{ ySplit: 1 }]; // 保存文件 workbook.xlsx.writeBuffer().then(buffer => { const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'table.xlsx'; a.click(); });}4. 常见问题解决