使用openpyxl调整Excel的宽度

逐行加载Excel,并将行宽调整为行中的最大字符数。

希望在打开 Excel 时能够看到所有字符。

失败代码:

python 复制代码
#失败代码:
wb = openpyxl.load_workbook('./targetExcelFile.xlsx')
ws = wb.worksheets[0]

for col in ws.iter_cols():
    max_length = 0
    column = col[0].column
    
    for cell in col:

        if cell.value == None:
            continue

        if len(str(cell.value)) > max_length:
            max_length = len(str(cell.value))

    ws.column_dimensions[column].width = adjusted_width

运行结果:

python 复制代码
Traceback (most recent call last):
  File "pypy.py", line 10, in main
    ws.column_dimensions[column].width = adjusted_width
  File "/.pyenv/versions/3.7.8/lib/python3.7/site-packages/openpyxl/utils/bound_dictionary.py", line 25, in __getitem__
    setattr(value, self.reference, key)
  File "/.pyenv/versions/3.7.8/lib/python3.7/site-packages/openpyxl/descriptors/base.py", line 42, in __set__
    raise TypeError('expected ' + str(self.expected_type))
TypeError: expected <class 'str'>

我收到一个错误,所以我进行了调查

如果你看一下调查的内容...

复制代码
 - ws1.column_dimensions[column].width = adjustment_width
 + ws1.column_dimensions[col[0].column_letter].width = adjustment_width
 由于在openpyxl 3及更高版本中,column_dimensions的下标已从列号的数值更改为列名称的字符串。

原来如此。

修正处:

python 复制代码
# 修正前
column = col[0].column

# 修正后
column = col[0].column_letter

修正后的代码

python 复制代码
wb = openpyxl.load_workbook('./targetExcelFile.xlsx')
ws = wb.worksheets[0]

for col in ws.iter_cols():
    max_length = 0
    column = col[0].column_letter
    
    for cell in col:

        if cell.value == None:
            continue

        if len(str(cell.value)) > max_length:
            max_length = len(str(cell.value))

    ws.column_dimensions[column].width = adjusted_width

修改成功,没问题。

相关推荐
得闲喝茶15 小时前
跨表数据匹配——VLOOKUP、XLOOKUP
大数据·数据库·笔记·信息可视化·数据分析·excel
AI刀刀2 天前
豆包智能体对话导出后,如何构建长期归档与高效检索体系?
android·人工智能·word·excel·ai导出鸭
ZX0X学习中2 天前
一句话让 AI 生成 Excel 多文件合并工具:码道 CLI 实战
人工智能·excel·ai编程·华为云码道
得闲喝茶2 天前
Excel——数据透析表
数据库·经验分享·笔记·其他·信息可视化·excel
小弥儿2 天前
无需安装WPS 和 Office!开源 OfficeCLI,Claude/Copilot 可直接调用,自动生成编辑Word/PPT/Excel
word·powerpoint·excel
Metaphor6923 天前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
花 满 楼3 天前
EB引脚配置自动化方案|告别手动繁琐配PIN,Excel+Python批量生成ARXML实现一键配置
python·excel·eb
用户298698530143 天前
Python 实现 Excel 新旧格式互转:告别 Office 依赖的自动化方案
后端·python·excel
未来之窗软件服务4 天前
Excel物业台帐租金合同资产—万象EXCEL应用(28) —东方仙盟
excel·仙盟创梦ide·东方仙盟·万象excel
AI刀刀4 天前
豆包智能体 7 月 15 日全面下线:技术解读、数据迁移与自动化备份方案
运维·人工智能·自动化·word·excel·ai导出鸭