I have some code that imports an image and converts it to an excel spreadsheet pixel by pixel. However, I’ve only been able to write the RGB into the cell and want to colour the cell instead.
I’m using html and javascript. My code is copied below. I haven’t found much in the way of googling, but if I’ve missed something obvious please let me know!
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);
}
3
Answers
You can use the fill property in the style of each cell. You’ll need to modify the code to include the style information for each cell.
If you need to download you can create blob after converting the data a worksheet like this
Unfortunately, the XLSX.js library does not support cell background color or any other cell styling. This is because the library focuses on data, and not on styling or formatting.
If you want to color cells based on their RGB values, you would need to use a library that supports Excel cell styling. One such library is ExcelJS.
Here’s an example of how you could modify your code to use ExcelJS and set the fill of each cell to its corresponding RGB color:
In this code, rgbToArgb is a helper function that converts RGB values to ARGB, which is the format ExcelJS uses for colors. The fill property of a cell is used to set the background color of the cell. The type is set to ‘pattern’ and the pattern is set to ‘solid’ to create a solid color fill. The fgColor is set to the ARGB color.
Please note that you’ll need to install the exceljs package to use this code. You can do this by running npm install exceljs in your project directory.
To fill an Excel spreadsheet with color using the xlsx library in JavaScript, you can modify your code to include style information along with the cell data. Here’s how you can modify your createExcelWorkbook function to fill the cells with color: