将格式应用于整行Openpyxl

Mat*_*ttR 5 python excel openpyxl

我有一个我要格式化的Excel文件.第一行(不包括Headers,所以row2)应该是红色和斜体.

Openpyxl文档状态:

如果要将样式应用于整个行和列,则必须自己将样式应用于每个单元格

我个人认为这很臭...这是我的解决方法:

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)
Run Code Online (Sandbox Code Playgroud)

第一个缺点是,如果有更多的单元格,例如A24我的循环,则会将格式应用于它.我可以用正则表达式解决这个问题.这是正确的方法吗?

最终 - 是否有更好的方法将格式应用于整行?也.任何人都可以指出我正确的方向一些好的 Openpyxl文档?我只发现了堆栈sheet.iter_rows()cell.coordinates堆栈.

Mar*_*ans 22

如果您只想更改第二行的颜色,则无需迭代所有行,您可以按如下方式迭代单行:

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)
Run Code Online (Sandbox Code Playgroud)

给你这样的东西:

excel屏幕截图

openpyxl文档中描述了访问多个单元格:访问许多单元格


或者,使用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)
Run Code Online (Sandbox Code Playgroud)

  • 它是在文档中,但有点埋没可能[访问许多单元格](http://openpyxl.readthedocs.io/en/default/tutorial.html#accessing-many-cells). (2认同)
  • 如果您要格式化很多单元格,那么`NamedStyles`就是您的选择. (2认同)