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

修改成功,没问题。

相关推荐
刘_sy7 小时前
使用EasyExcel和多线程实现高效数据导出
java·excel·easyexcel·批量导出excel
PowerBI学谦12 小时前
Copilot:Excel中的Python高级分析来了
python·excel·copilot
E-iceblue2 天前
Python 合并 Excel 单元格
python·excel·合并
sszdzq2 天前
Excel 合并列数据
excel
prince_zxill2 天前
Excel中不用复杂公式根据指定X列的数值N复制整行数据N行简单方法
excel
VBAMatrix3 天前
DeepSeek操作Excel,实现图表自动化生成
运维·自动化·excel·wps·deepseek
一醉千秋3 天前
excel中单元格字符串提取数字累加
excel
VB.Net3 天前
19.4.9 数据库方式操作Excel
数据库·c#·excel
真就死难3 天前
CSV格式和普通EXCEL格式文件的区别
linux·excel
朵朵zeng3 天前
Excel文件的读取
python·excel