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:
There is no need to iterate on all of the rows if you only intend to change the colour for the second row, you can just iterate over a single row as follows:
import openpyxl
from openpyxl import load_workbook
from openpyxl.styles import Font
file = 'input.xlsx'
wb = load_workbook(filename=file)
ws = wb['Output']
red_font = Font(color='00FF0000', italic=True)
# Enumerate the cells in the second row
for cell in ws["2:2"]:
cell.font = red_font
wb.save(filename=file)
Giving you something like:
Accessing multiple cells is described in the openpyxl docs: Accessing many cells
The format "2:2"
enumerates the cells over a single row. If "2:3"
is used, this will return the cells a row at a time, i.e. row 2 then row 3 and so would need an additional loop.
Alternatively, to use a NamedStyle
:
import openpyxl
from openpyxl import load_workbook
from openpyxl.styles import Font, NamedStyle
file = 'input.xlsx'
wb = load_workbook(filename=file)
ws = wb['Output']
# Create a NamedStyle (if not already defined)
if 'red_italic' not in wb.named_styles:
red_italic = NamedStyle(name="red_italic")
red_italic.font = Font(color='00FF0000', italic=True)
wb.add_named_style(red_italic)
# Enumerate the cells in the second row
for cell in ws["2:2"]:
cell.style = 'red_italic'
wb.save(filename=file)