简体   繁体   English

使用openpyxl更改整个excel表的列宽

[英]change the columns width of entire excel sheet using openpyxl

I want to change all columns width of multiple sheets in my excel file.我想更改我的 excel 文件中多个工作表的所有列宽。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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