【问题标题】:Applying Format to Entire Row Openpyxl将格式应用于整行 Openpyxl
【发布时间】:2017-03-23 15:20:53
【问题描述】:

我有一个要格式化的 Excel 文件。第一行(不包括标题,所以第 2 行)应该是红色并斜体

Openpyxl Documentation states

如果您想将样式应用于整个行和列,那么您必须自己将样式应用于每个单元格

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

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,我的循环将对其应用格式。我可以用正则表达式解决这个问题。那会是正确的方法吗?

最终,是否有更好的方法将格式应用于整行?还有。任何人都可以为我指出一些good Openpyxl 文档的正确方向吗?我只在 Stack 上发现了 sheet.iter_rows()cell.coordinates

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    如果您只打算更改第二行的颜色,则无需遍历所有行,您可以按如下方式遍历单行:

    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

    "2:2" 格式枚举单行上的单元格。如果使用"2:3",这将一次返回一行单元格,即第 2 行然后第 3 行,因此需要一个额外的循环。


    或者,使用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)
    

    【讨论】:

    • 谢谢!这是我希望记录的类型。我不知道你可以这样索引。事实上,鉴于这种方法,我引用的文档 sn-p 非常具有误导性。
    • 它在文档中,但可能有点隐藏Accessing many cells
    • 如果你有很多单元格要格式化,那么NamedStyles 是要走的路。
    • @CharlieClark 我以前用过NamedStyle,但你如何将它应用到我的案例中?
    • 链接断开:Accessing many cells
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多