我有一个我要格式化的Excel文件。第一行(不包括Headers,因此row2)应为红色,斜体。
Openpyxl Documentation states:
如果要将样式应用于整个行和列,则必须自己将样式应用于每个单元格
我个人认为这很臭...这是我的解决方法:
A24
第一个缺点是如果有更多单元格,例如sheet.iter_rows()
,我的循环将应用格式化。我可以用正则表达式解决这个问题。这是正确的方法吗?
最终 - 是否有更好的方法将格式应用于整行?此外。任何人都可以指出我正确的方向一些良好的 Openpyxl文档?我只在Stack上发现了cell.coordinates
和body {
height: 100vh;
background: green;
overflow: hidden;
}
。
答案 0 :(得分:20)
如果您只打算更改第二行的颜色,则无需迭代所有行,您可以按如下方式迭代单行:
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)
给你类似的东西:
openpyxl文档中描述了访问多个单元格:Accessing many cells
或者,使用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)