问题
I am trying to read an ".xlsx" file consisting of a table with some cells that are having a color fill (cell background color).
Using "Python 3.4" and "openpyxl 2.5.12", I tried to create a dummy yellow cell fill on "a1" and saved the file, when opening the "xlsx" file I can see it was yellow highlighted. However, when I loop through the spreadsheet cells with the condition:
if cell.fill == yellowFill:
print(cell.value)
I do only get the value of "a1", knowing that there are other cells having the same yellow fill.
I did even try to go to Excel's color palette to compare the fill color code of the dummy "a1" cell and the other yellow highlighted cells, it was the same (Red: 255, Green: 255, Blue: 0)!!!
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, colors, Fill
p = 'some_directory\example.xlsx'
wb = load_workbook(p)
ws = wb['Sheet1']
yellowFill = PatternFill(start_color = colors.YELLOW,
end_color = colors.YELLOW,
fill_type='solid')
ws['a1'].fill = yellowFill
wb.save(p)
for row in ws.rows:
for cell in row:
if cell.fill == yellowFill:
print(cell.value)
Is there a way to print out only the cell values that are having a yellow fill?
An update: I have tried to look at the difference between the dummy highlighted cell and the originally highlighted cell:
print(ws['a1'].value)
print(ws['a1'].fill)
print()
print(ws['e5'].value)
print(ws['e5'].fill)
And got the following output:
>>>
1
<openpyxl.styles.fills.PatternFill object>
Parameters:
patternType='solid', fgColor=<openpyxl.styles.colors.Color object>
Parameters:
auto=None, type='rgb', indexed=None, tint=0.0, rgb='00FFFF00', theme=None,
bgColor=<openpyxl.styles.colors.Color object>
Parameters:
auto=None, type='rgb', indexed=None, tint=0.0, rgb='00FFFF00', theme=None
4
<openpyxl.styles.fills.PatternFill object>
Parameters:
patternType='solid', fgColor=<openpyxl.styles.colors.Color object>
Parameters:
auto=None, type='rgb', indexed=None, tint=0.0, rgb='FFFFFF00', theme=None,
bgColor=<openpyxl.styles.colors.Color object>
Parameters:
auto=None, type='indexed', indexed=64, tint=0.0, rgb=None, theme=None
>>>
Many thanks in advance!
回答1:
As requested in the comments:
Try with:
cell.fill.fgColor.rgb == '00FFFF00'
来源:https://stackoverflow.com/questions/53948928/openpyxl-is-there-a-way-to-search-an-excel-spreadsheet-for-cells-with-specific