如何使用 exceljs javascript 在导出 excel 工作表中的列标题上添加样式

How to add styling on column heading in export excel sheet using exceljs javascript

提问人:Raheel Aslam 提问时间:11/17/2023 最后编辑:Raheel Aslam 更新时间:11/17/2023 访问量:37

问:

我想在导出 excel 工作表的列标题中添加样式,但此脚本不起作用。我尝试使用不同的方法,但样式对工作表没有影响。

function exportReportGroups() {
    const table = document.getElementById('rep_groupingTable_data');

    // Create a new Workbook
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.table_to_sheet(table);
    // Define the style for the header cells
    const headerStyle = {
        fill: {
            patternType: 'solid',
            fgColor: { rgb: '36a7c4' } // Background color (#36a7c4)
        },
        font: {
            color: { rgb: 'ffffff' } // Text color (white)
        }
    };
    // Loop through the range of cells in the first row (header row)
    for (let col in ws) {
        if (col.startsWith('A1')) {
            ws[col].s = headerStyle; // Apply header style to each cell in the header row
        }
    }
    // Set the worksheet in the Workbook
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // Generate Excel file
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
    }
    const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
    saveAs(blob, 'Report.xlsx');
}
// HTML
<div id="report_expor_table_data_se">
<table style="border-bottom: 1px solid #dddee2" id="rep_groupingTable_data" width="100%" cellpadding="0" cellspacing="0" class="report_grouping_table">
<thead id="rep_grouping_header" style="text-align: left;background: #36a7c4;border-bottom: 1px solid #dddee2;"><tr><th style="white-space:nowrap;text-align: left;padding: 10px 10px;font-size: 14px;color: #fff;line-height: 1.5em;border-left: 1px solid #ffffff;"></th><th style="white-space:nowrap;text-align: left;padding: 10px 10px;font-size: 14px;color: #fff;line-height: 1.5em;border-left: 1px solid #ffffff;"></th><th style="white-space:nowrap;text-align: center;padding: 10px 10px;font-size: 14px;color: #fff;line-height: 1.5em;border-left: 1px solid #ffffff;" class="sorting_disabled" colspan="1">Health And Safety</th><th style="white-space:nowrap;text-align: center;padding: 10px 10px;font-size: 14px;color: #fff;line-height: 1.5em;border-left: 1px solid #ffffff;" class="sorting_disabled" colspan="2">Adherence To&nbsp; The Schedules Of Duties</th></tr></thead>
 <tbody id="rep_grouping_body">
</tbody>
</table></div>

请看看是否可以使用 JavaScript 完成。

enter image description here

JavaScript Excel

评论

0赞 Raheel Aslam 11/23/2023
嗨,是否可以在 excel 工作表上形成?
0赞 Raheel Aslam 11/23/2023
@all我已经把这个例子 jsfiddle.net/v473grka/5

答: 暂无答案