首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >利用XLRD包识别Excel表格单元格颜色编码

利用XLRD包识别Excel表格单元格颜色编码
EN

Stack Overflow用户
提问于 2011-11-03 06:56:18
回答 4查看 36K关注 0票数 33

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-11-03 07:29:07

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

代码语言:javascript
运行
AI代码解释
复制
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的更多信息。

票数 43
EN

Stack Overflow用户

发布于 2020-04-21 11:46:14

JMax建议的解决方案只适用于xls文件,不适用于xlsx文件。这将引发一个NotImplementedError: formatting_info=True not yet implemented。仍未更新适用于xlsx文件的Xlrd库。所以你必须每次Save As和改变格式,这可能对你不起作用。

这是一个使用openpyxl库的xlsx文件的解决方案。A2是我们需要了解其颜色代码的单元格。

代码语言:javascript
运行
AI代码解释
复制
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
票数 7
EN

Stack Overflow用户

发布于 2017-09-29 07:09:26

此函数以元组形式返回单元格背景的RGB值。

代码语言:javascript
运行
AI代码解释
复制
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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7991209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档