Openpyxl 格式不适用于工作簿

问题描述 投票:0回答:1

Excel 工作簿只有一个工作表“DuckSheet”。该表包含三列。其中两列包含 True 或 False 的二进制值:

An formatted workbook

它的目的是格式化两个二进制值列。存在一个字典,其中键 =(Excel 工作簿的)工作表名称,键 =(键 = 列名称,值 = True 或 False)的字典。 True 或 False 值是应应用“bad_format”的值。如果 A 列的值为 True,则 A 列中的 True 值将应用“bad_format”。

工作簿已打开,使用定制函数生成格式,并使用另一个定制函数按列应用格式:

workbook_full_file_path = ("ducks.xlsx")
duck_checks_by_column = {"DuckSheet": {'IsPecking?': False, 'IsOutofLake': True}}
format_bad = generate_bad_format()

wb = openpyxl.load_workbook(filename=workbook_full_file_path)
for ws in wb:
    rules = duck_checks_by_column[ws.title]  # Get out dictionary of formatting rules by column using the sheet name.
    apply_formats_by_column(worksheet=ws, rules_by_column=rules, format_to_apply=format_bad)

一个函数用于使用 openpyxl 生成一种格式,称为“bad_format”:

def generate_bad_format():
    """

    Returns: A format as a list of structure [Fill, Font]

    """

    red_fill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
    black_color_font = '000000'
    black_font = openpyxl.styles.Font(size=11, bold=True, color=black_color_font)
    bad_format = [red_fill, black_font]
    return bad_format

使用 apply_format_by_column 函数应用格式:

def apply_formats_by_column(worksheet, rules_by_column, format_to_apply):
    """

    Args:
        worksheet: An openpyxl Excel sheet object.
        rules_by_column: A dictionary of rules by column name where column name is key and value is either True or
        False. The value given indicates which binary should have the "bad" formatting applied, indicating a result
        that requires fixing.
        format_to_apply: A list of openpyxl format rules where List[0] = Fill and List[1] = Font.

    Returns: Nothing. The sheet is formatted in place.

    """

    last_row = worksheet.max_row + 1  # Assumes the same last row for all columns, which should be the case.

    for col_name, value_for_bad_format in rules_by_column.items():
        for column_cells in worksheet.iter_cols(1, worksheet.max_column): # iterate column cells by column.
            if column_cells[0].value == col_name:
                column_number_to_format = column_cells[0].column
                print(f"TESTING: A column has been found to format:\n\nName: {col_name}\nNumber: {column_number_to_format}")
                for row in range(1, last_row):
                    cell = worksheet.cell(row=row, column=column_number_to_format)
                    print(f"TESTING: Now formatting this cell: {cell} with:\nFill: {format_to_apply[0]}\nFont: {format_to_apply[1]}")
                    cell.fill = format_to_apply[0]
                    cell.font = format_to_apply[1]

添加了两条以“TESTING”开头的打印行。通过控制台输出,这些显示正在选择正确的单元格和格式。例如,“IsPecking?”的单元格 B4列为 False,因此用于格式化。控制台输出:

TESTING: A column has been found to format:

Name: IsPecking?
Number: 2

...

TESTING: Now formatting this cell: <Cell 'DuckSheet'.B4> with:
Fill: <openpyxl.styles.fills.PatternFill object>
Parameters:
patternType='solid', fgColor=<openpyxl.styles.colors.Color object>
Parameters:
rgb='00EE1111', indexed=None, auto=None, theme=None, tint=0.0, type='rgb', bgColor=<openpyxl.styles.colors.Color object>
Parameters:
rgb='00EE1111', indexed=None, auto=None, theme=None, tint=0.0, type='rgb'
Font: <openpyxl.styles.fonts.Font object>
Parameters:
name=None, charset=None, family=None, b=True, i=False, strike=None, outline=None, shadow=None, condense=None, color=<openpyxl.styles.colors.Color object>
Parameters:
rgb='00000000', indexed=None, auto=None, theme=None, tint=0.0, type='rgb', extend=None, sz=11.0, u=None, vertAlign=None, scheme=None

代码运行,但没有将格式应用于单元格。代码或方法有什么错误?

python-3.x openpyxl
1个回答
0
投票

必须通过 openpyxl 保存工作簿才能保存结果。这应该在加载工作簿并应用格式后在“main”区域中完成。应使用完整的输出文件路径。更改“main”代码以包含保存行:

workbook_full_file_path = ("ducks.xlsx") duck_checks_by_column = {"DuckSheet": {'IsPecking?': False, 'IsOutofLake': True}} 格式错误=生成错误格式()

wb = openpyxl.load_workbook(filename=workbook_full_file_path)
for ws in wb:
    rules = duck_checks_by_column[ws.title]  # Get out dictionary of formatting rules by column using the sheet name.
    apply_formats_by_column(worksheet=ws, rules_by_column=rules, format_to_apply=format_bad)
wb.save(workbook_full_file_path)
© www.soinside.com 2019 - 2024. All rights reserved.