openpyxl 和 excel 渲染版本之间的字体颜色不一致

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

我需要用Python读取一个Excel文件并获取一个特定单元格的字体颜色。我的此列有时包含在 Excel 中正确呈现的红色值(字体颜色)。 当我在 openpyxl 中加载相同的文件时,我的值不一致。例如:

  • 我有一个在Excel中以黑色字体呈现的“代码”列。 输入:
    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”)时,我有相同的输出: 输入:
    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
python excel colors fonts openpyxl
1个回答
0
投票

Excel 可以访问自己的渲染引擎和主题定义,而 openpyxl 无法解释这些。当单元格的字体颜色定义为 RGB 值时,openpyxl 可以直接读取它,如红色字体单元格的示例所示 (

giacord_cell.font.color returns 'FFFF0000'
)。

但是,在处理主题单元格(

like code_cell
pr_cell1
)时,字体颜色是使用主题索引和色调而不是显式 RGB 值来定义的。 openpyxl 在字体颜色属性中提供了主题索引和色调,但它不会自动计算渲染颜色。

要计算主题单元格的实际颜色,可能需要手动将主题索引映射到工作簿主题中相应的基本 RGB 颜色。

但是,您也可以考虑使用 xlwings 或 pywin32,它们直接与 Excel 应用程序交互,无需手动解释主题和色调。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.