如何更改代码以用颜色填充 Excel 电子表格?

问题描述 投票:0回答:1

我有一些代码可以导入图像并将其逐像素转换为 Excel 电子表格。但是,我只能将 RGB 写入单元格,并希望为单元格着色。

我正在使用 html 和 javascript。我的代码复制如下。我没有通过谷歌搜索找到太多东西,但如果我错过了一些明显的东西,请告诉我!

    function createExcelWorkbook(imageData, width, height) {
        const wb = XLSX.utils.book_new();
        const wsData = [];

        for (let y = 0; y < height; y++) {
            const rowData = [];
            for (let x = 0; x < width; x++) {
                const pixelIndex = (y * width + x) * 4; // Each pixel has 4 values (R, G, B, A)
                const red = imageData[pixelIndex];
                const green = imageData[pixelIndex + 1];
                const blue = imageData[pixelIndex + 2];
                rowData.push(`RGB(${red}, ${green}, ${blue})`);
            }
            wsData.push(rowData);
        }
javascript html excel rgb
1个回答
0
投票

您可以在每个单元格的样式中使用填充属性。您需要修改代码以包含每个单元格的样式信息。

function createExcelWorkbook(imageData, width, height) {
    const wb = XLSX.utils.book_new();
    const wsData = [];

    for (let y = 0; y < height; y++) {
        const rowData = [];
        for (let x = 0; x < width; x++) {
            const pixelIndex = (y * width + x) * 4;
            const red = imageData[pixelIndex];
            const green = imageData[pixelIndex + 1];
            const blue = imageData[pixelIndex + 2];

            // Create a style object with the desired fill color
           const style = {
               fill: {
                   fgColor: { rgb: `FF${red.toString(16).padStart(2, '0')}${green.toString(16).padStart(2, '0')}${blue.toString(16).padStart(2, '0')}` }
               }
           };

            // Push an object representing both the cell value and style into rowData
            rowData.push({ v: '', s: style });
        }
        wsData.push(rowData);
    }

    // Convert the data to a worksheet and add it to the workbook
    const ws = XLSX.utils.aoa_to_sheet(wsData);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // Create a blob and download the workbook
    const blob = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'blob' });
    saveAs(blob, 'imageData.xlsx');
}

© www.soinside.com 2019 - 2024. All rights reserved.