简体   繁体   中英

Is there a way to condense this code instead of using a big if-else block?

Writing a function that applies styles to a cell range, wondering if there's some sort of metaprogramming way to avoid having a big if-else block here. Like being able to get which attribute I want to set from a dictionary that maps from Type -> attribute.

def _apply_style_to_range(self, cell_range, style):
    for row in self.worksheet[cell_range]:
        for cell in row:
            if isinstance(style, openpyxl.styles.Alignment):
                self.worksheet[cell.coordinate].alignment = style
            elif isinstance(style, openpyxl.styles.Border):
                self.worksheet[cell.coordinate].border = style
            elif isinstance(style, openpyxl.styles.PatternFill):
                self.worksheet[cell.coordinate].fill = style
            elif isinstance(style, openpyxl.styles.Font):
                self.worksheet[cell.coordinate].font = style
            elif style in Numbers.all_number_formats: # these are custom strings I came up with so no defining type
                self.worksheet[cell.coordinate].number_format = style
            else:
                raise ValueError('unhandled style {} unable to be applied'.format(style))

This is what I was able to come up with

def _apply_style_to_range(self, cell_range, style):
    style_dict = {
        openpyxl.styles.Alignment: "alignment",
        openpyxl.styles.Border: "border",
        openpyxl.styles.PatternFill: "fill",
        openpyxl.styles.Font: "font",
    }

    attr_to_set = style_dict.get(type(style), None)
    if attr_to_set is None and style in Numbers.all_number_formats:
        attr_to_set = "number_format"

    if attr_to_set is None:
        raise ValueError('unhandled style {} unable to be applied'.format(style))

    for row in self.worksheet[cell_range]:
        for cell in row:
            self.worksheet[cell.coordinate].__setattr__(attr_to_set, style)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM