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

修改成功,没问题。

相关推荐
allbs8 小时前
spring boot项目excel导出功能封装——4.导入
spring boot·后端·excel
m5655bj10 小时前
使用 Python 高效复制 Excel 行、列、单元格
开发语言·python·excel
温轻舟1 天前
Python自动办公工具01-Excel文件编辑器
开发语言·python·编辑器·excel·温轻舟
WarPigs1 天前
Unity编辑器开发笔记
unity·编辑器·excel
allbs1 天前
spring boot项目excel导出功能封装——3.图表导出
spring boot·后端·excel
lqz19931 天前
根据html导出excel和word
html·word·excel
12程序猿1 天前
postman调用文件(.xlsm---带宏的excel文件)下载接口成功下载excel文件,浏览器访问下载文件打不开
excel·lua·postman
刻BITTER2 天前
用EXCEL 将单色屏幕的Bitmap 字模数据还原回图形
单片机·嵌入式硬件·excel·arduino
匿者 衍2 天前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel
天外天-亮2 天前
Vue + excel下载 + 水印
前端·vue.js·excel