LoginSignup
46
35

More than 5 years have passed since last update.

openpyxlでセル幅を自動設定する

Last updated at Posted at 2019-03-12

Introduction

以下のような実験データファイル(test.xlsx)があるとします。

スクリーンショット 2019-03-12 17.21.38.png

開いてみると、4行D列目やE列目全体が、セルに収まりきらずに表示できていない部分があります。データの数がこれだけなら手作業でセルの幅を広げてもよいですが、一気に設定してしまいたいという気にもなりますね。

スクリプトとその実行結果

この悩みを解消するスクリプトを以下に示します。

sheet_width.py

'''
    sheet_width.py
    purpose: make new xlsx and set width automatically
'''

import openpyxl as xl


# set input file name
inputfile = 'test.xlsx'

# read input xlsx
wb1 = xl.load_workbook(filename=inputfile)
ws1 = wb1.worksheets[0]

# set column width
for col in ws1.columns:
    max_length = 0
    column = col[0].column

    for cell in col:
        if len(str(cell.value)) > max_length:
            max_length = len(str(cell.value))

    adjusted_width = (max_length + 2) * 1.2
    ws1.column_dimensions[column].width = adjusted_width

# save xlsx file
wb1.save(inputfile)

実行結果は以下のようになります。

スクリーンショット 2019-03-12 17.28.03.png

スクリプト詳細

幅の指定

ws1.column_dimensions[column].width = adjusted_width

でcolumn列の幅をadjusted_widthに指定しています。

幅を自動で設定するために

# set column width
for col in ws1.columns:
    max_length = 0
    column = col[0].column

    for cell in col:
        if len(str(cell.value)) > max_length:
            max_length = len(str(cell.value))

    adjusted_width = (max_length + 2) * 1.2

for col in ws1.columns:で列によるループを行います。次にcolumn変数にcol[0].columnを代入することで、どの列のループを行なっているのかを記憶させます。次のfor cell in col:でその列の中に含まれるセルに対しての繰り返しを行うことができます。len(str(cell.value))で、セルの値が文字列としてどのくらいの長さかを算出し、その最大値を見つけ出しています。最後にそれに余裕を持たせた値をadjust_widthとして代入しています。

46
35
4

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
46
35