使用XLRD包识别Excel单元格颜色代码

38 投票
4 回答
46191 浏览
提问于 2025-04-17 05:33

我正在写一个Python脚本,用来从Excel表格中读取数据,使用的是xlrd这个库。工作表中有几个单元格是用不同的颜色标记的,我想知道这些单元格的颜色代码。有没有什么办法可以做到这一点呢?如果能给个例子就太好了。

4 个回答

5

这个函数会返回单元格背景的rgb值,结果是一个元组。

def getBGColor(book, sheet, row, col):
    xfx = sheet.cell_xf_index(row, col)
    xf = book.xf_list[xfx]
    bgx = xf.background.pattern_colour_index
    pattern_colour = book.colour_map[bgx]

    #Actually, despite the name, the background colour is not the background colour.
    #background_colour_index = xf.background.background_colour_index
    #background_colour = book.colour_map[background_colour_index]

    return pattern_colour
9

JMax 提出的解决方案只适用于 xls 文件,而不适用于 xlsx 文件。这会导致出现一个错误,提示 NotImplementedError: formatting_info=True not yet implemented。目前 Xlrd 库还没有更新到可以处理 xlsx 文件。所以每次你都得选择 另存为 并更改文件格式,这可能对你来说不太方便。
这里有一个使用 openpyxl 库处理 xlsx 文件的解决方案。A2 是我们需要找出颜色代码的单元格。

import openpyxl
from openpyxl import load_workbook
excel_file = 'color_codes.xlsx' 
wb = load_workbook(excel_file, data_only = True)
sh = wb['Sheet1']
color_in_hex = sh['A2'].fill.start_color.index # this gives you Hexadecimal value of the color
print ('HEX =',color_in_hex) 
print('RGB =', tuple(int(color_in_hex[i:i+2], 16) for i in (0, 2, 4))) # Color in RGB
46

这里有一种处理这个问题的方法:

import xlrd
book = xlrd.open_workbook("sample.xls", formatting_info=True)
sheets = book.sheet_names()
print "sheets are:", sheets
for index, sh in enumerate(sheets):
    sheet = book.sheet_by_index(index)
    print "Sheet:", sheet.name
    rows, cols = sheet.nrows, sheet.ncols
    print "Number of rows: %s   Number of cols: %s" % (rows, cols)
    for row in range(rows):
        for col in range(cols):
            print "row, col is:", row+1, col+1,
            thecell = sheet.cell(row, col)      
            # could get 'dump', 'value', 'xf_index'
            print thecell.value,
            xfx = sheet.cell_xf_index(row, col)
            xf = book.xf_list[xfx]
            bgx = xf.background.pattern_colour_index
            print bgx

更多信息可以在这个Python-Excel Google Group找到。

撰写回答