【问题标题】:Get Excel cell background color in pandas read_excel?在pandas read_excel中获取Excel单元格背景颜色?
【发布时间】:2018-05-31 03:01:19
【问题描述】:

我有一个 Excel 文件,其中的单元格具有背景颜色。我正在使用read_excel 将该文件读入pandas。有没有办法获取单元格的背景颜色?

【问题讨论】:

  • 您可能需要考虑下拉到xlrd(Pandas 使用它)来获取颜色信息。
  • 如果我幸运的话会尝试回到这里!

标签: python excel pandas


【解决方案1】:

上面建议的解决方案仅适用于xls 文件,不适用于xlsx 文件。这引发了NotImplementedError: formatting_info=True not yet implementedXlrd 库仍未更新以适用于 xlsx 文件。所以你必须Save As 并每次更改格式,这可能不适合你。
这是使用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

【讨论】:

  • 在我的例子中,这种方法给出了不准确的结果(即没有正确捕捉颜色)。
  • 我为我的项目检查了它,它工作得很好。你能分享你的例子吗?
【解决方案2】:

我根据this link 编辑了上面@csaladenes 响应中的代码sn-p,它适用于我的xls 文件(原始导致所有单元格显示相同的颜色索引,尽管它们具有不同的背景颜色):

import xlrd
import numpy as np
wb = xlrd.open_workbook(file, formatting_info=True)
sheet = wb.sheet_by_name("mysheet")
bgcol=np.zeros([sheet.nrows,sheet.ncols])
for row in range(sheet.nrows):
    for col in range(sheet.ncols):
        c = sheet.cell(row, col)
        cif = sheet.cell_xf_index(row, col)
        iif = wb.xf_list[cif]
        cbg = iif.background.pattern_colour_index
        bgcol[row,col] = cbg

【讨论】:

    【解决方案3】:

    按照Mark的建议,通过xlrd暴力破解:

    from xlrd import open_workbook
    wb = open_workbook('wb.xls', formatting_info=True)
    sheet = wb.sheet_by_name("mysheet")
    #create empy colormask matrix
    bgcol=np.zeros([sheet.nrows,sheet.ncols])
    #cycle through all cells to get colors
    for row in range(sheet.nrows):
      for column in range(sheet.ncols):
        cell = sheet.cell(row, column)  
        fmt = wb.xf_list[cell.xf_index]
        bgcol[row,column]=fmt.background.background_colour_index
    #return pandas mask of colors
    colormask=pd.DataFrame(bgcol) 
    

    但是,必须有更好的方法直接通过 pandas...

    【讨论】:

    • 不幸的是,formatting_info=True 仅适用于 .xls 但不适用于 .xlsx 文件:-( 无论如何,这是一个很好的提示 - 谢谢!
    • 不幸的是,它对我来说也不适用于 xls。我有几种背景颜色,矩阵导致所有单元格的颜色索引为 64 ..
    • @JoePhi 请看下面我的解决方案。它适用于 XLSX 文件。它以十六进制和 RGB 元组形式提供颜色代码。
    猜你喜欢
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2013-11-07
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多