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

38

我正在编写一个使用xlrd库从Excel表格读取数据的Python脚本。工作表中有一些单元格被用不同的颜色突出显示,我想要识别这些单元格的颜色代码。是否有任何方法可以做到这一点?如果能给出一个示例就更好了。

4个回答

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上可以找到更多信息。


该脚本能够识别颜色代码。但现在我遇到了一个不同的问题。我正在解析的Excel表格中有两个空单元格,没有任何额外的格式或颜色,即这两个单元格都具有白色背景和无文本内容,位置分别为(52,4)和(9,4)。在第一种情况下,颜色是64,在另一个单元格中颜色是9。为什么两个类似类型的单元格的颜色代码不同? - Kinjal
你确定你没有一个是“空白”而另一个是“无填充”吗? - JMax
颜色索引9表示白色,除非调色板已更改。 61是“系统”颜色索引;请阅读xlrd文档开头附近的有关颜色索引的部分。 “空”,“白色”和“内部没有文本”都很模糊。告诉我们单元格的类型,值和xf_index。使用repr(value)。您可能已经将默认格式应用于第4列; sheet.colinfo_map [4] .xf_index给您什么? - John Machin
2
我终于成功区分了单元格是否被高亮。检查是通过查找单元格的颜色映射来完成的。以下是代码: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]if color_map and (color_map[0] != 255 or color_map[1] != 255 or color_map[2] != 255): #worksheet Cell is highlighted else: #worksheet Cell is not highlighted因此,如果元组中没有任何一个值为255,则表示该单元格已经被高亮。 - Kinjal
4
这让我遇到了一个“NotImplementedError”的错误。很可能是因为我打开的是.xlsx而不是.xls文件导致的:“NotImplementedError:formatting_info = True尚未实现”。 - deeenes
2
不幸的是,这仅适用于“XLS”文件,而不适用于“XLSX”文件。有人有关于“XLSX”文件的解决方案吗?您将收到“NotImplementedError”。 - Sumit Pokhrel

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

@Heinz 我测试了多种情况,改变了很多颜色。它完全正常工作。你能分享一下你的例子吗? - Sumit Pokhrel
在我的情况下,它会引发“TypeError: 'int' object is not subscriptable”,因为color_in_hex只是一个数字,例如6或7(即使颜色完全不同,如黄色和灰色,它们也可以是相邻的两个数字?),并且它是一个整数,这不是可订阅类型,因此无法执行[i:i + 2]。我尝试使用color_in_hex:str = f“#{str(color_in_hex).zfill(6)}”对齐它,以获得类似于#000007的东西,但是颜色仍然不正确。 - George Zorikov

4

该函数返回单元格背景的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

这是针对xlrd的,使用open_workbook(..., formatting_info=True),因此无法用于xlsx文件。 - Echo9k

0
# say you have an Excel file called workbook
 and inside it there is a worksheet called worksheet

# inside that worksheet is cell say C1 that is highlighted
 and you want to get the color value of the highlighted cell

# Trying the openpyxl package
import openpyxl

# Importing all modules from the openpyxl package
from openpyxl import *

# reading ev2 excel workbook through load_workbook function
workbook = load_workbook("C:PATHTO/workbook.xlsx")

# Accessing existing worksheets
worksheet = workbook ["worksheet"]

## METHOD1 ##

# Getting the highlight property of the cell
highlight=str(worksheet ['C1'].fill)

# Printing out the value of the color
index=int(highlight.find("rgb='"))
print(highlight[index+5:index+13])

## METHOD 2 ##

print(worksheet ['C11'].fill.start_color.index)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接