Reputation: 21
I need to read an excel file in python and get the font color of one particular cell. I have this column that sometimes contains a red value (font color) that is correctly rendered in excel. When i load the same file in openpyxl i have inconsistent values. For example:
code_cell.font.color
output:
<openpyxl.styles.colors.Color object> Parameters: rgb=None, indexed=None, auto=None, theme=1, tint=0.0, type='theme'
pr_cell1.font.color
output:
<openpyxl.styles.colors.Color object> Parameters: rgb=None, indexed=None, auto=None, theme=1, tint=0.0, type='theme'
THIS TWO SHOULD BE DIFFERENT!giacord_cell.font.color
output:
<openpyxl.styles.colors.Color object> Parameters: rgb='FFFF0000', indexed=None, auto=None, theme=None, tint=0.0, type='rgb'
There is a way to obtain the rendered color of a themed cell? how is it possible that excel sucesfully render the color while openpyxl can tell the differences between two themed cell?
Thank you.
this is the code i used to read the excel file.
from openpyxl import Workbook, load_workbook
wb = load_workbook(file_path, rich_text=True) ##file_path is a string
ws = wb.active
rows = [ i for i in ws.iter_rows()]
code_cell = r[code_index] ##integer index
pr_cell= r[pr_index] ##integer index
pr_cell1= r[pr_index1] ##integer index
giacord_cell = r[giacord_index] ##integer index
Upvotes: 2
Views: 72
Reputation: 21
Excel has access to its own rendering engine and theme definitions, which openpyxl does not interpret. When a cell’s font color is defined as an RGB value, openpyxl can read it directly, as seen in your example for the cell with the red font (giacord_cell.font.color returns 'FFFF0000'
).
However, when dealing with themed cells (like code_cell
and pr_cell1
), the font color is defined using a theme index and tint rather than an explicit RGB value.
openpyxl provides the theme index and tint in the font color properties, but it won't automatically calculate the rendered color.
To calculate the actual color of a themed cell, it might be necessary to manually map the theme index to the corresponding base RGB color from the workbook's theme.
However, you can also consider using xlwings or pywin32, which interact directly with the Excel application and bypass the need to interpret themes and tints manually.
Upvotes: 2