LoginSignup
1
1

More than 1 year has passed since last update.

openpyxlでエクセルの横幅を合わせる操作

Last updated at Posted at 2022-12-06

エクセルを1行ずつ読み込み行の幅を行の最大文字数に合わせて
エクセルを開いた時に、全ての文字を見える状態にしたかった。
少しつまづいたのでメモで残しておきます。

失敗例
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'>

エラーが出たので調査してみたら
こちらの記事が見つかった
https://teratail.com/questions/295219

記事の内容を見てみると...

- ws1.column_dimensions[column].width = adjusted_width
+ ws1.column_dimensions[col[0].column_letter].width = adjusted_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

結果、問題なく修正が成功した。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1