使用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

修改成功,没问题。

相关推荐
vfvfb14 分钟前
excel对比找不同人名 双xlsx双列对比
excel·excel多列对比
課代表17 小时前
Excel VBA 为数据赋予随机浅色标记
excel·vba·可视化·条件格式·标记·对比·随机
kylezhao201921 小时前
C#上位机开发数据持久化:excel报表导入导出
开发语言·c#·excel
悟能不能悟21 小时前
springboot controller返回的是HttpServletResponse成功返回excel文件流,失败就返回失败参数
spring boot·后端·excel
野比带雄2 天前
対excel时间格式的理解
excel
缺点内向2 天前
Java:轻松实现 Excel 文档属性添加
java·开发语言·excel
Teable任意门互动2 天前
从飞书多维表格 简道云到Teable多维表格:企业为何选择Teable作为新一代智能数据协作平台?
数据库·excel·钉钉·飞书·开源软件
AC赳赳老秦2 天前
DeepSeek + Excel 实战:多表联动分析与异常数据自动预警教程
microsoft·rabbitmq·excel·etcd·memcached·memcache·deepseek
2501_930707782 天前
如何使用C#代码将 Excel 文件转换为 SVG
开发语言·c#·excel
Eiceblue2 天前
将 Python 列表导出为 Excel 文件:一维、二维、字典列表
开发语言·python·excel·visual studio code