我需要用Python读取一个Excel文件并获取一个特定单元格的字体颜色。我的此列有时包含在 Excel 中正确呈现的红色值(字体颜色)。 当我在 openpyxl 中加载相同的文件时,我的值不一致。例如:
code_cell.font.color
输出:
<openpyxl.styles.colors.Color object> Parameters: rgb=None, indexed=None, auto=None, theme=1, tint=0.0, type='theme'
pr_cell1.font.color
输出:
<openpyxl.styles.colors.Color object> Parameters: rgb=None, indexed=None, auto=None, theme=1, tint=0.0, type='theme'
这两个应该不同!giacord_cell.font.color
输出:
<openpyxl.styles.colors.Color object> Parameters: rgb='FFFF0000', indexed=None, auto=None, theme=None, tint=0.0, type='rgb'
有没有办法获取主题单元格的渲染颜色? excel 如何成功渲染颜色,而 openpyxl 可以区分两个主题单元之间的差异?
谢谢你。
这是我用来读取excel文件的代码。
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
Excel 可以访问自己的渲染引擎和主题定义,而 openpyxl 无法解释这些。当单元格的字体颜色定义为 RGB 值时,openpyxl 可以直接读取它,如红色字体单元格的示例所示 (
giacord_cell.font.color returns 'FFFF0000'
)。
但是,在处理主题单元格(
like code_cell
和 pr_cell1
)时,字体颜色是使用主题索引和色调而不是显式 RGB 值来定义的。
openpyxl 在字体颜色属性中提供了主题索引和色调,但它不会自动计算渲染颜色。
要计算主题单元格的实际颜色,可能需要手动将主题索引映射到工作簿主题中相应的基本 RGB 颜色。
但是,您也可以考虑使用 xlwings 或 pywin32,它们直接与 Excel 应用程序交互,无需手动解释主题和色调。