Reputation: 1
I am extremely new to Python, but haven't been able to find a solution through searches.
I have an Excel file that has important cells formatted either in bold or italics. I am trying to get Python to return ALL cells that are formatted in bold or italics. So far I have only been able to figure out how to get Python to identify if a given cell is in bold or italics.
import openpyxl as xl
file_path = '/Users/uiswork/Downloads/members_of_uni_bodies.xlsx'
wb = xl.load_workbook(file_path)
ws = wb.active
#changing to other worksheets:
#ws = wb["Title of the Worksheet"]
a1 = ws['A1']
print(a1.font) # lists the parameters of font (returns: i for italic )
print(a1.font.i == True)
>>> False
Upvotes: 0
Views: 316
Reputation: 9379
Here's a way to do what your question asks:
import openpyxl as xl
wb = xl.load_workbook('FormatTest.xlsx') #, read_only=True)
ws = wb.active
matchingCells = []
cells = ws._cells
for row, col in cells.keys():
cell = cells[row, col]
if cell.font.italic or cell.font.bold:
matchingCells.append(cell)
for cell in matchingCells:
formatDesc = " and ".join(x[0] for x in [("italic", cell.font.italic), ("bold", cell.font.bold)] if x[1])
print(f'cell {cell.coordinate} with value "{cell.value}" is {formatDesc}')
Sample output:
cell B4 with value "AN ITALIC CELL (B4)" is italic
cell F11 with value "A BOLD CELL (F11)" is bold
cell K16 with value "AN ITALIC AND BOLD CELL (K16)" is italic and bold
Upvotes: 1