简体   繁体   中英

change the columns width of entire excel sheet using openpyxl

I want to change all columns width of multiple sheets in my excel file. What I found in other posts was about changing the width of one column. How can I do this?

This is what I tried but failed:

 wb = openpyxl.load_workbook('my_file.xlsx')
    for sheet in wb.worksheets:
        for column in sheet.columns:
            sheet.column_dimensions[column].width = 50

Hi you can use the following code this one build for dynamic cell resize but can use for your purpose also

column_widths = []
for row in data:
    for i, cell in enumerate(row):
        if len(column_widths) > i:
            if len(cell) > column_widths[i]:
                column_widths[i] = 50
        else:
            column_widths += [50]

for i, column_width in enumerate(column_widths):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

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