使用openpyxl调整Excel的宽度

逐行加载Excel,并将行宽调整为行中的最大字符数。
希望在打开 Excel 时能够看到所有字符。

失败代码:

#失败代码:
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

运行结果:

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的下标已从列号的数值更改为列名称的字符串。

原来如此。

修正处:

# 修正前
column = col[0].column

# 修正后
column = col[0].column_letter

修正后的代码

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

修改成功,没问题。

你可能感兴趣的:(python,excel,python)