如何使用 python 获取 xlsx 文件中给定单元格的 RGB 值?

How can I get the RGB value of a given cell in a xlsx file using python?

给定一行和一列(加上 sheet 名称),我需要一种方法来从 python 脚本中提取单元格的 rgb 值,如 excel 中所报告的那样.

我一直在使用 openpyxl。以下内容无法始终如一地工作:

cell.fill.fgColor.rgb
cell.fill.bgColor.rgb

以下给出了错误的值:

openpyxl.styles.colors.COLOR_INDEX[cell.fill.fgColor.index]
openpyxl.styles.colors.COLOR_INDEX[cell.fill.fgColor.index]

所以我正在寻找另一种方法来做到这一点。可能的解决方案不必局限于 openpyxl 库,因为我愿意使用另一个库。

如果对 Windows 使用 Python,请考虑 win32com 库,因为它可以访问 Excel 对象库并使用其任何方法和属性,例如 Workbooks.Open, Interior.Color, Workbook.Close.

将这个有趣的 link 用于 RGB value extraction,您可以将 VBA 翻译成 Python。具体来说,VBA 的整数除法运算符反斜杠 \ 转换为 Python 的双正斜杠 // 和 VBA 中的模运算符mod 变成 Python 的 %

下面输出黄色单元格的 RGB。包括两种单元格引用类型。整个例程包含在 try/except/finally 中以关闭后台进程并释放资源,无论是否出现运行时错误。

import win32com.client as win32

def getRGB(xlCell):
    C = xlCell.Interior.Color

    R = C % 256
    G = C // 256 % 256
    B = C // 65536 % 256

    return "R={}, G={}, B={}".format(R, G, B)

try:
    xlApp = win32.gencache.EnsureDispatch('Excel.Application')
    wb = xlApp.Workbooks.Open('C:\Path\To\Workbook.xlsx')
    ws = wb.Worksheets('RESULTS')

    print(getRGB(ws.Range("A2")))      # A1 Style Reference
    # R=255, G=255, B=0  (yellow-colored cell)

    print(getRGB(ws.Cells(2,1)))       # R1C1 Style Reference 
    # R=255, G=255, B=0  (yellow-colored cell)

    wb.Close(False)
    xlApp.Visible = False    

except Exception as e:
    print(e)

finally:
    xlApp.Quit
    ws = None
    wb = None
    xlApp = None

此外,请注意 VBA 不是 MS Excel 的一部分,而是一个外部组件(默认连接到软件)。它只是连接到 Excel 的对象库的另一种语言,因为此处使用 Python 演示的任何编程语言都可以为该库创建一个 COM 接口。

@Parfait 的解决方案非常好。但是我改进了getRGB(),我觉得shifting会比冗余N分区好:

def getRGB(xlCell):
    C = int(xlCell.Interior.Color)

    R = C & 255
    G = C >> 8 & 255
    B = C >> 16 & 255

    return "R={}, G={}, B={}".format(R, G, B)