You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Excel列宽自动适配:openpyxl无效后的解决方法

批量Excel工作簿列宽自动适配:解决openpyxl方法无效问题

尝试为多个Excel工作簿设置列宽自动适配,使用openpyxl编写了如下代码,运行无报错,但无法实现列宽自动调整以完整显示所有文本的效果:

from openpyxl.utils import get_column_letter
import openpyxl

files = ['A.xlsx', 'B.xlsx', 'C.xlsx', 'D.xlsx', 'E.xlsx']
for file in files:
    wb = openpyxl.load_workbook('exported_data/' + file)
    for sheet in range(len(wb.worksheets)):
        ws = wb.worksheets[sheet]
        for i in range(1, ws.max_column + 1):
            ws.column_dimensions[get_column_letter(i)].bestFit = True
            ws.column_dimensions[get_column_letter(i)].auto_size = True

改用xlwings可以成功实现需求,代码如下:

import xlwings as xw

files = ['A.xlsx', 'B.xlsx', 'C.xlsx', 'D.xlsx', 'E.xlsx']
for file in files:
    with xw.App(visible=False) as app:
        wb = xw.Book('exported_data/' + file)
        for sheet in range(len(wb.sheets)):
            ws = wb.sheets[sheet]
            ws.autofit()
        wb.save()
        wb.close()

内容的提问来源于stack exchange,提问作者Tea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:21:28