
pythonでExcelの結合セルを一括で解除結合されていたセルに同じデータをコピーする


フォルダ内のすべての.xlsxファイルを取得し、既に処理されたファイル(ファイル名にS.xlsxが含まれるもの)は対象外とします。
各ファイルの全シートに対して、以下の処理を行います:
シート内に存在するすべての結合セルを解除します。
結合が解除されたセル範囲に対して、元の結合セルの左上にあったデータを全てのセルに複製します。
この際、複製されたセル範囲を5色のパステルカラー(パステルオレンジ、パステルグリーン、パステルブルー、パステルピンク、パステルイエロー)で塗り分け、隣接する範囲ごとに異なる色を適用します。
編集が完了したファイルは、元のファイル名にS.xlsxを付加した名前で保存します。
import openpyxl
from datetime import datetime
from openpyxl.styles import PatternFill
import os
# 処理対象のフォルダを指定
input_folder = ドライブ":\フォルダ"
output_suffix = "S.xlsx" # 出力ファイル名に付加するサフィックス
# 優しい色合いの5色を定義
fill_colors = [
PatternFill(start_color="FFEBCC", end_color="FFEBCC", fill_type="solid"), # パステルオレンジ
PatternFill(start_color="CCFFCC", end_color="CCFFCC", fill_type="solid"), # パステルグリーン
PatternFill(start_color="CCCCFF", end_color="CCCCFF", fill_type="solid"), # パステルブルー
PatternFill(start_color="FFCCCC", end_color="FFCCCC", fill_type="solid"), # パステルピンク
PatternFill(start_color="FFFFCC", end_color="FFFFCC", fill_type="solid") # パステルイエロー
]
# フォルダ内のすべてのExcelファイルに対して処理を行う
for filename in os.listdir(input_folder):
if filename.endswith(".xlsx") and not filename.endswith(output_suffix):
input_file = os.path.join(input_folder, filename)
output_file = os.path.join(input_folder, filename.replace(".xlsx", output_suffix))
# Excelファイルを読み込む
wb = openpyxl.load_workbook(input_file)
# 全てのシートに対して処理を行う
for ws in wb.worksheets:
# 結合セルの範囲をリストとしてコピー
merged_ranges = list(ws.merged_cells.ranges)
# 色を切り替えるためのインデックス
color_index = 0
# 結合セルの解除とデータの複製
for merged_range in merged_ranges:
# 結合範囲の左上セルの値を取得
top_left_cell = ws.cell(merged_range.min_row, merged_range.min_col)
value = top_left_cell.value
# 日付データの場合、時刻を除外
if isinstance(value, datetime):
value = value.date() # 時刻を除外して日付のみを取得
# 結合セルを解除
ws.unmerge_cells(str(merged_range))
# 現在の色を選択
fill_color = fill_colors[color_index]
# 結合されていたセル範囲内にデータを複製し、塗りつぶし
for row in range(merged_range.min_row, merged_range.max_row + 1):
for col in range(merged_range.min_col, merged_range.max_col + 1):
cell = ws.cell(row, col)
cell.value = value
cell.fill = fill_color # 塗りつぶしを適用
# 次の結合セル範囲では色を切り替える
color_index = (color_index + 1) % 5 # 0から4までを循環
# 編集後のファイルを保存
wb.save(output_file)
print(f"ファイル {filename} の処理が完了し、保存されました: {output_file}")