Gộp File Từng File Excel vào 1 File (1 người xem)

Liên hệ QC

Người dùng đang xem chủ đề này

Tôi tuân thủ nội quy khi đăng bài

vinhnguyen2204

Thành viên mới
Tham gia
26/5/25
Bài viết
3
Được thích
2
Nhờ anh/chị hổ trợ giúp em cần làm 1 File excel tổng hợp Trong tháng 7 có 30 File - Gộp thành 1 File với 30 Sheet chỉ sử dụng Sheet có dữ liệu Pivot sẵn . Tính tổng COD và trung bình Trọng lượng tính phí . Em có làm mẫu tham khảo như vậy nhưng làm từng File thì sẻ mất thời gian . Nên nhờ anh/chị cao nhân hướng dẫn em có phương pháp nào nhanh . em có tìm hiểu công cụ Combine Data trong Excel nhưng ko rỏ phương pháp . Phiền anh chị hướng dẫn em kèm 1 File mẫu để em tham khảo . Em xin cảm ơn rất nhiều --- Dead line dí quá T__T
 

File đính kèm

  • Dữ liệu Pivot gồm COD - Trọng lượng tính phí.png
    Dữ liệu Pivot gồm COD - Trọng lượng tính phí.png
    28.6 KB · Đọc: 11
  • screenshot_1757122850.png
    screenshot_1757122850.png
    74.3 KB · Đọc: 11
  • 03.07.2025.xlsx
    03.07.2025.xlsx
    71.5 KB · Đọc: 5
  • 01.07.2025.xlsx
    01.07.2025.xlsx
    54.2 KB · Đọc: 4
  • 02.07.2025.xlsx
    02.07.2025.xlsx
    73.7 KB · Đọc: 8
  • Mẫu.png
    Mẫu.png
    46.4 KB · Đọc: 10
Lần chỉnh sửa cuối:
Thay vì gộp thành 30 sheet thì tôi gộp thành 1 sheet được không? Lấy file về, sửa đưởng dẫn thư mục chứa 30 file và nhấn refresh
 

File đính kèm

Em bổ sung luôn giải pháp bằng Pythol . COD đã chỉnh sửa để xuất đúng yêu cầu theo mẫu em mong muốn .
Giữ nguyên sheet Pivot (không lấy dữ liệu gốc, chỉ lấy dữ liệu tổng hợp sẵn).

Gộp thành 1 file Excel mới với:

Mỗi ngày = 1 sheet (tên sheet theo tên file: 01.07, 02.07, … 30.07).

Mỗi sheet chứa đúng bảng Pivot đã có trong file gốc.

Thêm 1 sheet Tổng hợp cuối cùng:

Cột: Ngày – Tổng COD – Trung bình Trọng lượng tính phí.

Tất cả dữ liệu trong mọi sheet đều được căn giữa (center).

Vẫn giữ auto-fit chiều rộng cột.
Các sheet ngày giữ đầy đủ dữ liệu, chỉ xoá dòng “Unnamed”.

Sheet Tổng hợp giữ nguyên 3 cột, hiển thị số có dấu phẩy + trọng lượng 2 chữ số thập phân.
Em gửi kèm File Pythol và File excel mẫu sau khi xuất để a/e tham khảo
A/e tải về mở bằng NOTE chỉnh đường dẫn trong đoạn code :
folder = Path(r"Đường dẫn Folder lưu trữ dữ liệu cần gộp")
files = sorted(folder.glob("*.xlsx"))
Rồi chạy là auto - ae có thể tham khảo Chat GPT nếu muốn điều chỉnh thêm phù hợp . Mong sẻ có ích với a/e nào cần . Xin chân thành cảm ơn
Bài đã được tự động gộp:

import pandas as pd
from pathlib import Path
from datetime import datetime
from openpyxl.utils import get_column_letter
from openpyxl import load_workbook
from openpyxl.styles import Alignment

# Thư mục chứa file Excel theo ngày
folder = Path(r" đường dẫn Folder chứa dữ liệu cần gộp ")
files = sorted(folder.glob("*.xlsx"))

# File Excel kết quả
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = folder / f"TongHop_Thang7_{timestamp}.xlsx"

def find_header_row(df, search_rows=15):
for i in range(min(search_rows, len(df))):
row = df.iloc.astype(str).fillna("")
text = " ".join(row.tolist()).lower()
if ("row labels" in text) or ("sum of" in text) or ("cod" in text) or ("trọng" in text):
return i
return df.head(search_rows).notna().sum(axis=1).idxmax()

def get_day_name(p: Path):
parts = p.stem.split(".")
return parts[0] + "." + parts[1] if len(parts) >= 2 else p.stem

summary_rows = []

with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
for file in files:
day_name = get_day_name(file)
try:
raw = pd.read_excel(file, sheet_name=0, header=None)

# Xoá các dòng chứa "Unnamed"
mask_unnamed = raw.astype(str).apply(
lambda s: s.str.contains("Unnamed", case=False, na=False)
).any(axis=1)
raw = raw[~mask_unnamed].reset_index(drop=True)

if raw.empty:
pd.DataFrame().to_excel(writer, sheet_name=day_name, index=False)
summary_rows.append([day_name, 0, 0.0])
continue

# Xác định dòng header
hrow = find_header_row(raw, search_rows=15)
header = raw.iloc[hrow].astype(str).tolist()
df = raw.iloc[hrow + 1 :].copy()
df.columns = header
df = df.reset_index(drop=True)

# Tìm Grand Total trong df gốc (trước khi format chuỗi)
df_raw = raw.iloc[hrow + 1:].copy()
df_raw.columns = header
df_raw = df_raw.reset_index(drop=True)

gt_mask = df_raw.astype(str).apply(
lambda s: s.str.contains("Grand Total", case=False, na=False)
).any(axis=1)

if not gt_mask.any():
summary_rows.append([day_name, 0, 0.0])
else:
gt = df_raw[gt_mask].iloc[0]

# Xác định cột COD và Trọng lượng
def find_col(cols, keywords):
for c in cols:
sc = str(c).lower()
if any(k in sc for k in keywords):
return c
return None

cod_col = find_col(df_raw.columns, ["cod"])
w_col = find_col(df_raw.columns, ["trọng", "trong luong", "trọng lượng"])

total_cod = pd.to_numeric(gt.get(cod_col, 0), errors="coerce") if cod_col else 0
avg_weight = pd.to_numeric(gt.get(w_col, 0), errors="coerce") if w_col else 0

total_cod = 0 if pd.isna(total_cod) else float(total_cod)
avg_weight = 0 if pd.isna(avg_weight) else float(avg_weight)

summary_rows.append([day_name, total_cod, avg_weight])

# Format COD có dấu phẩy trong tất cả các sheet
cod_col = next((c for c in df.columns if "COD" in str(c).upper()), None)
if cod_col:
df[cod_col] = pd.to_numeric(df[cod_col], errors="coerce")
df[cod_col] = df[cod_col].fillna(0).astype(int).map("{:,}".format)

# Ghi sheet đã làm sạch
df.to_excel(writer, sheet_name=day_name, index=False)

except Exception:
summary_rows.append([day_name, 0, 0.0])

# Tạo sheet "Tổng hợp" (giữ cả 3 cột)
summary_df = pd.DataFrame(summary_rows, columns=["Ngày", "Tổng COD", "Trọng lượng tính phí"])
summary_df["Tổng COD"] = summary_df["Tổng COD"].map(lambda x: f"{x:,.0f}")
summary_df["Trọng lượng tính phí"] = summary_df["Trọng lượng tính phí"].map(lambda x: f"{x:,.2f}")

summary_df.to_excel(writer, sheet_name="Tổng hợp", index=False)

# Auto-fit độ rộng cột + canh giữa dữ liệu
wb = load_workbook(output_file)
for ws in wb.worksheets:
for col_cells in ws.columns:
width = 0
for cell in col_cells:
if cell.value is not None:
width = max(width, len(str(cell.value)))
# Căn giữa
cell.alignment = Alignment(horizontal="center", vertical="center")
ws.column_dimensions[get_column_letter(col_cells[0].column)].width = width + 2
wb.save(output_file)

print(f"✅ Đã tạo file tổng hợp: {output_file}")
 

File đính kèm

Bài viết mới nhất

Back
Top Bottom