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

修改成功,没问题。

相关推荐
jllllyuz9 分钟前
VC++ 读写 Excel 文件实现
开发语言·c++·excel
fengyehongWorld11 分钟前
Excel 函数式编程相关的公式
excel
开开心心_Every1 天前
进程启动瞬间暂停工具,适合调试多开
运维·服务器·gitee·pdf·开源·电脑·excel
葡萄城技术团队1 天前
表格工具栏:像 Excel 只是起点,按需定制才是关键
excel
开开心心就好1 天前
直接减少蓝光辐射的专业护眼工具
linux·运维·服务器·智能手机·excel·java-rabbitmq·sdkman
得闲喝茶2 天前
SQL处理数据的常用语法语句
数据库·笔记·sql·数据分析·excel
hmywillstronger2 天前
【Python】从SAP2000 XML截面库提取数据到Excel
xml·python·excel
抹茶咖啡2 天前
IT运维的365天--045 WPS突然就不能正常打开Excel文件了
excel·it运维·wps
专注VB编程开发20年2 天前
在 Python 中使用 comtypes 时,大小写通常必须保持精确
python·excel