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

Kin*_*jal 27 python excel xlrd

我正在编写一个python脚本,使用xlrd从excel表中读取数据.工作表中的几个单元格用不同颜色突出显示,我想识别单元格的颜色代码.有没有办法做到这一点?一个例子将非常感激.

JMa*_*Max 37

以下是处理此问题的一种方法:

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
Run Code Online (Sandbox Code Playgroud)

有关Python-Excel Google Group的更多信息.

  • 我终于设法区分了一个细胞是否突出显示.通过查找单元格的颜色映射来完成检查.以下是代码:book = xlrd.open_workbook("sample.xls",formatting_info = 1)xfx = sheet.cell_xf_index(row,col)xf = book.xf_list [xfx] bgx = xf.background.pattern_colour_index color_map = book. colour_map [bgx]如果color_map和(color_map [0]!= 255或color_map [1]!= 255或color_map [2]!= 255):#worksheet单元格突出显示:#worksheet单元格未突出显示因此,如果没有元组中的值为255,表示单元格突出显示. (2认同)
  • 这对我提出了一个“ NotImplementedError”。可能是因为我打开了xlsx而不是xls:NotImplementedError:formatting_info = True尚未实现。 (2认同)
  • 不幸的是,这仅适用于“XLS”文件,不适用于“XLSX”文件。有人对“XLSX”文件有任何解决方案吗?您将收到“NotImplementedError”。 (2认同)

Jin*_*Heo 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
Run Code Online (Sandbox Code Playgroud)


Sum*_*rel 5

JMax 建议的解决方案仅适用于xls文件,不适用于xlsx文件。这引发了一个NotImplementedError: formatting_info=True not yet implemented. Xlrd库仍未更新以适用于xlsx文件。因此,您Save As每次都必须更改格式,这可能对您不起作用。
这是xlsx使用openpyxl库的文件的解决方案。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
Run Code Online (Sandbox Code Playgroud)