Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have compatibility openpyxl and pyxlsb, using openpyxlI have done some code to style the cells accordingly but I need to compress the code or just avoid nested for loops or itertools. For following requirements I have tried code:

What I have tried:

1) Here for 1st row i need to get bgcolor:8A2BE2 and text should be bold and WHITE:
if '1' in cell.coordinate and len(cell.coordinate) == 2:
                    cell.font = Font(color=colors.WHITE, bold=True)
                    cell.fill = PatternFill(start_color='8A2BE2', end_color='8A2BE2', fill_type='solid')

2) for A and B cols i need some bgcolor:YELLOW and all-border:
for x in cell.coordinate:
                        if x[0] == 'A' or x[0] == 'B':
                            cell.fill = PatternFill(start_color=colors.YELLOW, end_color=colors.YELLOW, fill_type='solid')
                bd = Side(color="000000")
                cell.border = Border(left=bd, top=bd, right=bd, bottom=bd)

3) for all cols i need to increase width to cell.value:
if cell.value:
                dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value)))) 
    for col, value in dims.items():
        result_sheet.column_dimensions[col].width = value

Full Code:
#for styling
    dims = {}
    for row in result_sheet.iter_rows():
        for cell in row:
            cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
            if '1' in cell.coordinate and len(cell.coordinate) == 2:
                cell.font = Font(color=colors.WHITE, bold=True)
                cell.fill = PatternFill(start_color='8A2BE2', end_color='8A2BE2', fill_type='solid')
            else:
                for x in cell.coordinate:
                    if x[0] == 'A' or x[0] == 'B':
                        cell.fill = PatternFill(start_color=colors.YELLOW, end_color=colors.YELLOW, fill_type='solid')
            bd = Side(color="000000")
            cell.border = Border(left=bd, top=bd, right=bd, bottom=bd)
            if cell.value:
                dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value)))) 
    for col, value in dims.items():
        result_sheet.column_dimensions[col].width = value
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900