-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_by_sheet.py
More file actions
384 lines (339 loc) · 15.4 KB
/
merge_by_sheet.py
File metadata and controls
384 lines (339 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# -*- coding: utf-8 -*-
"""
============================================
Excelファイル結合ツール
============================================
プログラム名: merge_by_sheet.py
作成者 : PSC 平野 翔士
作成日 : 2025年8月25日
説明 : このプログラムは、Excelファイルを同名シートごとに縦結合するためのものです。
使用方法: プログラムを実行
最終更新日: 2025年8月25日
最終更新者: PSC 平野 翔士
変更履歴:
日付 バージョン 変更内容
---------- ---------- -----------------------------------
2025/08/25 1.0 初版作成
--------------------------------------------
## 要件定義
- GUIにドラッグアンドドロップしたファイルを結合
- GUIに取り込んだファイルを並べ替えることができる
- GUIに取り込んだファイルを削除することができる
- 選択したファイルを削除
- すべてのファイルを削除
- 設定項目
- 結合シート名(ホワイトリスト)
- ヘッダーの行数設定
- 結合の出力先を指定できる
- 実行したら同一シート名ごとに結合したExcelファイルを出力する
"""
"""
ExcelファイルをGUIで選択/ドラッグ&ドロップし、
同名シートごとに縦結合して出力するツール。
主な機能:
- ファイルのドラッグ&ドロップ(tkinterdnd2)
- ファイルリストの順序変更(↑/↓)
- 選択削除/全削除
- 結合対象シートのホワイトリスト(カンマ区切り)
- ヘッダー行番号の指定(0=1行目がヘッダー)
- 保存先の指定
- 同名シートごとに列ユニオンで縦結合(欠損は空欄)
- 追跡列 _source_file, _source_sheet を付与
"""
#-----------------------------------------------
# Livelary Import
#-----------------------------------------------
import re
from typing import Any
import pandas as pd
from pathlib import Path
from datetime import datetime
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinterdnd2 import DND_FILES, TkinterDnD
# --- tkinterdnd2 が無くても起動できるようにする(DnDなしで動作) ---
DND_AVAILABLE = True
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
except Exception:
DND_AVAILABLE = False
#-----------------------------------------------
# ユーティリティ関数
#-----------------------------------------------
# Excelファイルかどうかのチェック
def is_excel_file(path: str) -> bool:
"""対応拡張子チェック(基本は xlsx/xlsm/xls だけに絞るのが安定)"""
return str(path).lower().endswith((".xlsx", ".xlsm", ".xls"))
# ファイル名のみ取得(スペース・日本語対応)
def parse_dnd_paths(dnd_payload: str) -> list[str]:
"""
DnDで受け取る文字列をファイルパス配列へ。
スペース・日本語対応のため {} やクォートを外しつつ分割。
"""
# {C:/aa bb/ccc.xlsx} {D:/テスト.xlsx}
parts = re.findall(r"\{.*?\}|[^\s]+", dnd_payload)
clean = [p.strip("{}") for p in parts]
return clean
#-----------------------------------------------
# 結合ロジック(テストしやすいようGUIから分離)
#-----------------------------------------------
# Excelファイルを同名シートごとに縦結合して保存
def merge_by_sheet(files: list[Path], sheet_whitelist: list[str], header_row: int, out_path: Path) -> None:
"""
指定ファイル群を、同名シートごとに縦結合して out_path に保存する。
- files: 結合対象Excel(順序はこのまま維持)
- sheet_whitelist: 指定があれば、そのシート名のみ結合(空なら全シート)
- header_row: pandas.read_excel の header に渡す値(0=1行目をヘッダー)
- out_path: 出力先 .xlsx
"""
buckets: dict[str, list[Any]] = {} #辞書型。キー=シート名、値=DataFrameリスト
# 各ファイルを処理
for f in files:
try:
with pd.ExcelFile(f) as xf:
target_sheets = xf.sheet_names
if sheet_whitelist:
# ホワイトリスト(完全一致)。trimして比較
wl = [s.strip() for s in sheet_whitelist if s.strip()]
target_sheets = [s for s in xf.sheet_names if s in wl]
for sheet in target_sheets:
try:
# 文字列で読み込み → 型ブレ最小化(必要ならあとで変換)
df = pd.read_excel(xf, sheet_name=sheet, header=header_row, dtype=str)
if df.empty:
continue
# 追跡列を付与
df["_source_file"] = f.name
df["_source_sheet"] = sheet
buckets.setdefault(str(sheet), []).append(df)
# シートが読み込めなかった
except Exception as e:
print(f"[WARN] 読み込み失敗: {f.name} / {sheet}: {e}")
continue
# Excelファイルが開けなかった
except Exception as e:
print(f"[WARN] 開けませんでした: {f.name}: {e}")
continue
# どのシートも読み込めなかった
if not buckets:
raise RuntimeError("どのシートも読み込めませんでした。ホワイトリスト・ヘッダー設定を確認してください。")
# 書き出し
out_path.parent.mkdir(parents=True, exist_ok=True)
with pd.ExcelWriter(out_path, engine="openpyxl") as writer:
for sheet_name, df_list in buckets.items():
try:
merged = pd.concat(df_list, ignore_index=True, sort=False) # 列ユニオン
# Excelのシート名31文字制限
safe_name = sheet_name[:31] if len(sheet_name) > 31 else sheet_name
merged.to_excel(writer, sheet_name=safe_name, index=False)
except Exception as e:
print(f"[WARN] 書き出し失敗: {sheet_name}: {e}")
continue
#-----------------------------------------------
# GUI 本体
#-----------------------------------------------
# クラス:ExcelMergerGUI
class ExcelMergerGUI:
"""画面・イベント・結合起動を司るクラス"""
# コンストラクタ
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("Excel Merger - 同名シート縦結合")
self.root.geometry("820x520")
# ファイル格納(順序を保持)
self.files: list[Path] = []
# GUI要素の構築
self._build_widgets()
# ---- 画面構築 ----
def _build_widgets(self):
pad: dict[str, Any] = {"padx": 8, "pady": 6}
# === 上段:ファイル操作 ===
# ファイル操作フレーム
frm_files = ttk.LabelFrame(self.root, text="ファイル")
frm_files.pack(fill="both", expand=False, **pad)
# ファイル追加ボタン
btn_add = ttk.Button(frm_files, text="ファイルを追加", command=self.on_add_files)
btn_add.grid(row=0, column=0, **pad)
# ファイル並べ替え(↑上へ移動)
btn_up = ttk.Button(frm_files, text="↑ 上へ", command=self.on_move_up)
btn_up.grid(row=0, column=1, **pad)
# ファイル並べ替え(↓下へ移動)
btn_down = ttk.Button(frm_files, text="↓ 下へ", command=self.on_move_down)
btn_down.grid(row=0, column=2, **pad)
# ファイル削除(選択削除)
btn_del = ttk.Button(frm_files, text="選択削除", command=self.on_delete_selected)
btn_del.grid(row=0, column=3, **pad)
# ファイル削除(全削除)
btn_clear = ttk.Button(frm_files, text="全削除", command=self.on_clear)
btn_clear.grid(row=0, column=4, **pad)
# DnDヒント
lbl_hint = ttk.Label(frm_files, text="↓ここにドラッグ&ドロップでも追加できます")
lbl_hint.grid(row=0, column=5, sticky="w", **pad)
# ファイルリスト
self.lst = tk.Listbox(frm_files, selectmode=tk.EXTENDED, height=8)
self.lst.grid(row=1, column=0, columnspan=6, sticky="nsew", **pad)
frm_files.grid_columnconfigure(5, weight=1)
frm_files.grid_rowconfigure(1, weight=1)
# DnD 対応(tkinterdnd2 があれば)
if DND_AVAILABLE and isinstance(self.root, TkinterDnD.Tk):
self.lst.drop_target_register(DND_FILES) # type: ignore
self.lst.dnd_bind("<<Drop>>", self.on_drop) # type: ignore
else:
lbl_hint.configure(text="(DnD無効: tkinterdnd2 が未導入 or 非対応環境)")
# === 中段:設定 ===
# 設定項目
frm_opts = ttk.LabelFrame(self.root, text="設定")
frm_opts.pack(fill="x", expand=False, **pad)
# 結合シート名の設定(カンマ区切り)
ttk.Label(frm_opts, text="結合シート名(カンマ区切り。空なら全シート)").grid(row=0, column=0, sticky="w", **pad)
self.ent_whitelist = ttk.Entry(frm_opts, width=60)
self.ent_whitelist.grid(row=0, column=1, columnspan=3, sticky="we", **pad)
# ヘッダー行番号の設定(0=ヘッダーなし、1=1行目がヘッダー、2=2行目がヘッダー...)
ttk.Label(frm_opts, text="ヘッダー行番号(0=ヘッダーなし、1=1行目、2=2行目...)").grid(row=1, column=0, sticky="w", **pad)
self.ent_header = ttk.Entry(frm_opts, width=10)
self.ent_header.insert(0, "0")
self.ent_header.grid(row=1, column=1, sticky="w", **pad)
# 保存先
ttk.Label(frm_opts, text="保存先").grid(row=2, column=0, sticky="w", **pad)
self.out_var = tk.StringVar()
self.ent_out = ttk.Entry(frm_opts, textvariable=self.out_var, width=60)
self.ent_out.grid(row=2, column=1, sticky="we", **pad)
# 保存先参照ボタン
btn_browse = ttk.Button(frm_opts, text="参照…", command=self.on_browse_out)
btn_browse.grid(row=2, column=2, **pad)
# 保存先既定値ボタン
frm_opts.grid_columnconfigure(1, weight=1)
# === 下段:実行 ===
# 実行フレーム
frm_run = ttk.Frame(self.root)
frm_run.pack(fill="x", side="top", expand=False, **pad)
# 実行ボタン
self.btn_run = ttk.Button(frm_run, text="結合を実行", command=self.on_run, width=30)
self.btn_run.pack(side="top")
# 既定の保存名をセット
self._set_default_outname()
# ---- イベント群 ----
def on_add_files(self):
paths = filedialog.askopenfilenames(
title="Excelファイルを選択",
filetypes=[("Excel", "*.xlsx *.xlsm *.xls")]
)
self._add_paths(paths)
# ドラッグ&ドロップでファイル追加
def on_drop(self, event):
paths = parse_dnd_paths(event.data)
self._add_paths(paths)
# インベントリにファイルを追加
def _add_paths(self, paths):
added = 0
for p in paths:
if is_excel_file(p):
path = Path(p)
if path.exists() and path not in self.files:
self.files.append(path)
self.lst.insert(tk.END, str(path))
added += 1
if added == 0 and paths:
messagebox.showwarning("警告", "Excelファイル(.xlsx/.xlsm/.xls)のみ追加できます。")
# 選択行を一つ上へ
def on_move_up(self):
# 選択行を一つ上へ
sel = list(self.lst.curselection())
if not sel:
return
for i in sel:
if i == 0:
continue
# リスト入れ替え
self.files[i-1], self.files[i] = self.files[i], self.files[i-1]
txt = self.lst.get(i)
self.lst.delete(i)
self.lst.insert(i-1, txt)
# 再選択
self.lst.selection_clear(0, tk.END)
for i in [max(0, s-1) for s in sel]:
self.lst.selection_set(i)
# 選択行を一つ下へ
def on_move_down(self):
# 選択行を一つ下へ
sel = list(self.lst.curselection())
if not sel:
return
for i in reversed(sel):
if i >= self.lst.size() - 1:
continue
self.files[i+1], self.files[i] = self.files[i], self.files[i+1]
txt = self.lst.get(i)
self.lst.delete(i)
self.lst.insert(i+1, txt)
self.lst.selection_clear(0, tk.END)
for i in [min(self.lst.size()-1, s+1) for s in sel]:
self.lst.selection_set(i)
# 選択行を削除
def on_delete_selected(self):
sel = sorted(self.lst.curselection(), reverse=True)
for i in sel:
del self.files[i]
self.lst.delete(i)
# 全行を削除
def on_clear(self):
self.files.clear()
self.lst.delete(0, tk.END)
# 保存先参照
def on_browse_out(self):
p = filedialog.asksaveasfilename(
title="保存先を指定",
defaultextension=".xlsx",
filetypes=[("Excel", "*.xlsx")]
)
if p:
self.out_var.set(p)
# デフォルトの出力ファイル名をセット
def _set_default_outname(self):
stamp = datetime.now().strftime("%Y%m%d_%H%M")
self.out_var.set(str(Path.cwd() / f"output_{stamp}.xlsx"))
# 実行ボタン押下
def on_run(self):
if not self.files:
messagebox.showwarning("警告", "結合対象ファイルを追加してください。")
return
# 読み取りシート名の設定
# ホワイトリスト(カンマ区切り)→ リスト化
wl_raw = self.ent_whitelist.get().strip()
sheet_whitelist = [s.strip() for s in wl_raw.split(",")] if wl_raw else []
# ヘッダー行の設定
try:
header_row = int(self.ent_header.get().strip() or "0")
if header_row < 0:
raise ValueError
except ValueError:
messagebox.showerror("エラー", "ヘッダー行番号は0以上の整数で指定してください。")
return
# 出力ファイル名の設定
out = self.out_var.get().strip()
if not out:
messagebox.showwarning("警告", "保存先を指定してください。")
return
out_path = Path(out)
# 実行
try:
self.btn_run.configure(state="disabled")
merge_by_sheet(self.files, sheet_whitelist, header_row, out_path)
messagebox.showinfo("完了", f"結合が完了しました。\n出力: {out_path}")
except Exception as e:
messagebox.showerror("エラー", f"結合に失敗しました。\n{e}")
finally:
self.btn_run.configure(state="normal")
#-----------------------------------------------
# エントリーポイント
#-----------------------------------------------
def main():
# tkinterdnd2 が使えるなら DnD版のTk を、なければ通常Tk
if DND_AVAILABLE:
root = TkinterDnD.Tk()
else:
root = tk.Tk()
ExcelMergerGUI(root)
root.mainloop()
if __name__ == "__main__":
main()