Question

I came across a very peculiar thing. When I try to fill a cell in an excel worksheet with a solid colour it fills adjacent cells, sometimes even dozens. It's odd since I do exactly the same things successfully in other places of my code, it's just this one which is different. I'm slowly running out of ideas on what could be wrong and thought that maybe someone here had a similar issue and solved it. My relevant code is:

__incorrectUnitsColour__='FF33CC'
cell, sheet =GetCellFromDest(str(named_range.destinations),wb) # Returns the cell pointed to by the named_range, this should work fine as I use it a lot in other places.

cell.style.fill.fill_type=openpyxl.style.Fill.FILL_SOLID
cell.style.fill.start_color.index=__incorrectUnitsColour__

If you've got any thoughts on what could be wrong I'll be happy to hear them, they don't even need to work just to get me thinking in the right direction ;)

I've appended the above code with:

print cell.row
print cell.column

which returns, as expected, 2 G. I've also confirmed that, once every several runs, the extent to which the cells are highlighted, increases. It's even more peculiar than this, if I highlight other cells in the same worksheet using openpyxl the same range gets highlighted.

I've got a very strong feeling something is wrong with the worksheet settings but I have no idea what. Also, this error only shows up when I try to programmatically highlight more than 1 cell in the same worksheet.

What makes all this even more odd highlighting cells in different worksheets eventually causes the same range of cells to be highlighted.

FOLLOWUP QUESTION: Does openpyxl cache any of the worksheet/workbook data? Because this would explain such behaviour.

Was it helpful?

Solution

I've looked into this a lot more. If you're facing a similar issue please follow this question of mine which describes the causes for the above problem. As of now this is a known issue in openpyxl and some people are working on fixing this. So hopefully this bug (because it has been confirmed to be cause by a bug in the library) will be fixed soon.

What I can suggest to try and alleviate the problem is to always select only one cell which is not filled using openpyxl later when saving the workbook in Excel. Also try not to touch the formatted cells too much through Excel itself, just openpyxl. And if you do change the cell format through Excel make sure you only change one cell at a time - if you apply the same style to a range of cells the same range will be then changed when you format a cell using openpyxl.

As unsatisfactory as it is to me that's all I've heard of the authors and figured out myself so far.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top