简体   繁体   English

在 Excel 文件中,如何使用 openpyxl (Python) 查找单元格的背景颜色

[英]In a Excel file how to find the background color of a cell using openpyxl (Python)

`wb = openpyxl.load_workbook('file.xlsx',data_only=True)
fs_count_row = fs.max_row 
fs_count_col = fs.max_column 
for a in range(1,fs_count_row):
    cell_color = fs.cell(column=1, row=a)
    bgColor = cell_color.fill.bgColor.index
    fgColor = cell_color.fill.fgColor.index`

Tried using the above code.尝试使用上面的代码。 However, it works fine for some cells and give wrong output for some other cells.但是,它对某些单元格工作正常,而对其他一些单元格给出错误的 output。 Can I know the reason why?我能知道原因吗?

Column number was fixed to 1 always, that's why code is not picking up the cells outside of the first column.列号始终固定为1 ,这就是代码没有拾取第一列之外的单元格的原因。 Loop both rows and columns .循环行和列 Updated code below.更新了下面的代码。 I've added a print statement to provide the fgcolor and bgcolor of all the active cells along with the cell information.我添加了一个打印语句来提供所有活动单元格的 fgcolor 和 bgcolor 以及单元格信息。 In addition, I've added a condition to ignore the blank cells where there is no foreground or background color.此外,我添加了一个条件来忽略没有前景色或背景色的空白单元格。

Input:输入:

Cell A1 = Yellow
Cell A2 = Blank
Cell B1 = Black
Cell B2 = Red

Code:代码:

import openpyxl
wb = openpyxl.load_workbook('Excel.xlsx',data_only=True)
fs = wb.active
fs_count_row = fs.max_row 
fs_count_col = fs.max_column 
for row in range(1,fs_count_row+1):
    for column in range(1,fs_count_col+1):
        cell_color = fs.cell(column=column, row=row)
        bgColor = cell_color.fill.bgColor.index
        fgColor = cell_color.fill.fgColor.index
        if (bgColor=='00000000') or (fgColor=='00000000'):
            continue
        else:
            print("Background color of cell (",row,column, ") is", bgColor)
            print("Foreground color of cell (",row,column, ") is", fgColor)

Output: Output:

Background color of cell ( 1 1 ) is 64
Foreground color of cell ( 1 1 ) is FFFFFF00
Background color of cell ( 1 2 ) is 64
Foreground color of cell ( 1 2 ) is 1
Background color of cell ( 2 2 ) is 64
Foreground color of cell ( 2 2 ) is FFFF0000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM