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

修改成功,没问题。

相关推荐
qq_5469372713 小时前
office和WPS平替软件,可以打开Word_Excel_PPT
word·excel·wps
Teable任意门互动13 小时前
拆解 Teable 背后研发主体,开源多维表格平台实力与落地案例
开发语言·开源·excel·飞书·开源软件
Cloud_Shy61813 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 下篇)
python·plotly·数据分析·excel·numpy·pandas
Cloud_Shy6181 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 中篇)
python·数据分析·excel·pandas
udc小白1 天前
Excel实现LSTM示例
人工智能·深度学习·神经网络·机器学习·excel·lstm
码银1 天前
在若依框架中,使用easyExcel完成动态列导出
java·excel·ruoyi
开开心心就好1 天前
免费无广告的批量卸载与系统清理工具
linux·服务器·网络·智能手机·rabbitmq·excel·memcached
SunnyDays10112 天前
Java 读写 Excel 公式:从基础到高级的实战总结
java·开发语言·excel
Codiggerworld2 天前
Vim配置从0到1:打造专属编辑器
编辑器·vim·excel
E_ICEBLUE2 天前
Python 教程:快速复制 Excel 工作表
python·excel