Applying Format to Entire Row Openpyxl

不羁的心 提交于 2019-12-04 08:10:41

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


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.get_sheet_by_name('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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!