簡體   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`

嘗試使用上面的代碼。 但是,它對某些單元格工作正常,而對其他一些單元格給出錯誤的 output。 我能知道原因嗎?

列號始終固定為1 ,這就是代碼沒有拾取第一列之外的單元格的原因。 循環行和列 更新了下面的代碼。 我添加了一個打印語句來提供所有活動單元格的 fgcolor 和 bgcolor 以及單元格信息。 此外,我添加了一個條件來忽略沒有前景色或背景色的空白單元格。

輸入:

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

代碼:

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:

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