I have an Excel File that I want to format. The first row (excluding Headers so row2) should be red and italicized.
the Openpyxl Documentation states:
If you want to apply styles to entire rows and columns then you must apply the style to each cell yourself
I personally thinks this stinks... Here is my workaround:
import openpyxl from openpyxl.styles import NamedStyle from openpyxl import load_workbook from openpyxl.styles.colors import RED from openpyxl.styles import Font # I normally import a lot of stuff... I'll also take suggestions here. file = 'MY_PATH' wb = load_workbook(filename=file) sheet = wb.get_sheet_by_name('Output') for row in sheet.iter_rows(): for cell in row: if '2' in cell.coordinate: # using str() on cell.coordinate to use it in sheet['Cell_here'] sheet[str(cell.coordinate)].font = Font(color='00FF0000', italic=True) wb.save(filename=file)
The first downside is that if there are more cells such as A24
my loop will apply the formatting to it. I can fix this with a regular expression. Would that be the correct approach?
Ultimately- is there a better way to apply a format to the entire row? Also. Can anyone point me in the right direction to some good Openpyxl documentation? I only found out about sheet.iter_rows()
and cell.coordinates
on Stack.