0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[スニペット] OpenPyXlで動的に列の幅を設定する

Last updated at Posted at 2025-05-26
from openpyxl import Workbook
from openpyxl.utils import get_column_letter

def set_column_widths_based_on_longest_part(sheet, target_row):
    """
    指定した行(1-based index)のセルをスキャンし、
    改行で分割した中で最も長い文字列を基準に列幅を設定する。
    """
    col_widths = {}

    # target_row 行だけを見る
    for cell in sheet[target_row]:
        if cell.value and isinstance(cell.value, str):
            parts = cell.value.split('\n')
            # 改行で分割したすべての要素の最大長を取得
            max_len = max(len(p) for p in parts)

            col_idx = cell.column  # 1-based index
            # 同じ列でより長い要素があれば更新
            if col_idx not in col_widths or max_len > col_widths[col_idx]:
                col_widths[col_idx] = max_len

    # 列幅を設定(余白として +2)
    for col_idx, width in col_widths.items():
        letter = get_column_letter(col_idx)
        sheet.column_dimensions[letter].width = width + 2


# --- 使用例 ---
wb = Workbook()
ws = wb.active

# 13行目に改行入りデータをセット
ws['A13'] = "氏名\nやまだたろう"
ws['B13'] = "部署\n開発部\n第二開発課"
ws['C13'] = "役職\n主任"

# 13行目を基準に列幅を自動調整
set_column_widths_based_on_longest_part(ws, target_row=13)

wb.save("output.xlsx")
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?