将格式应用于整行Openpyx

2024-06-01 03:05:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Excel文件要格式化。第一行(不包括页眉,所以第2行)应为红色,并将斜体化

Openpyxl Documentation states

If you want to apply styles to entire rows and columns then you must apply the style to each cell yourself

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

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)

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

最终-是否有更好的方法将格式应用于整行?还有。有谁能给我指出一些好的Openpyxl文档的正确方向吗?我只在堆栈上发现了sheet.iter_rows()cell.coordinates


Tags: to方法infromimportyoucoordinatecell
1条回答
网友
1楼 · 发布于 2024-06-01 03:05:48

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

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)

给你这样的东西:

excel screen shot

访问多个单元格在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)

相关问题 更多 >