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

2024-05-16 16:01:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本,用xlrd从excel工作表中读取数据。工作表中很少有单元格用不同的颜色突出显示,我想标识单元格的颜色代码。有办法吗?举个例子真的很好。


Tags: 脚本颜色读取数据excel标识例子办法颜色代码
2条回答

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

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

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的更多信息。

相关问题 更多 >