
Python Automation Cho Dân Văn Phòng: Tự Động Xử Lý File, Email, PDF Và Web Scraping
Chia sẻ
"Tổng hợp 8 script Python thực tế cho dân văn phòng: gộp file Excel, rename hàng loạt, gửi email tự động, merge PDF, web scraping, tạo báo cáo tự động. Copy-paste và chạy ngay."
Bạn không cần trở thành developer — chỉ cần biết copy-paste và chỉnh sửa vài dòng Python, bạn đã có thể tự động hóa 80% công việc lặp đi lặp lại hàng ngày. Bài viết này tổng hợp 8 script thực tế, mỗi script giải quyết 1 bài toán cụ thể.

Script 1: Gộp Tất Cả File Excel Trong 1 Folder
Tình huống: 12 file báo cáo tháng, cần gộp thành 1 file duy nhất.
import pandas as pd
import glob
# Lấy tất cả file Excel trong folder
files = glob.glob("C:/BaoCao/*.xlsx")
# Đọc và gộp
all_data = []
for f in files:
df = pd.read_excel(f)
df["Nguon"] = f.split("/")[-1] # Thêm cột tên file
all_data.append(df)
result = pd.concat(all_data, ignore_index=True)
result.to_excel("TongHop.xlsx", index=False)
print(f"Gộp {len(files)} file → {len(result)} dòng")Script 2: Rename Hàng Loạt File
Tình huống: 200 file ảnh tên lộn xộn, cần đổi thành IMG_001.jpg, IMG_002.jpg...
import os
folder = "C:/AnhSanPham/"
prefix = "SP"
files = sorted(os.listdir(folder))
for i, f in enumerate(files, 1):
ext = os.path.splitext(f)[1] # .jpg, .png
new_name = f"{prefix}_{i:03d}{ext}" # SP_001.jpg
os.rename(
os.path.join(folder, f),
os.path.join(folder, new_name)
)
print(f"{f} → {new_name}")Script 3: Gửi Email Hàng Loạt Từ Danh Sách Excel
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Đọc danh sách từ Excel
df = pd.read_excel("DanhSach.xlsx")
# Cột: Email, Ten, SoTien
# Kết nối Gmail SMTP
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.starttls()
smtp.login("your_email@gmail.com", "app_password") # Dùng App Password
for _, row in df.iterrows():
msg = MIMEMultipart()
msg["Subject"] = f"Nhắc nhở thanh toán - {row['Ten']}"
msg["From"] = "your_email@gmail.com"
msg["To"] = row["Email"]
body = f"""
Kính gửi {row["Ten"]},
Chúng tôi xin nhắc nhở khoản thanh toán:
Số tiền: {row["SoTien"]:,.0f} VNĐ
Vui lòng thanh toán trước ngày 15 tháng này.
Trân trọng.
"""
msg.attach(MIMEText(body, "plain"))
smtp.send_message(msg)
print(f"✅ Sent to {row['Email']}")
smtp.quit()Lưu ý: Dùng App Password (không phải mật khẩu Gmail thường). Tạo tại myaccount.google.com → Security → 2-Step Verification → App passwords.
Script 4: Merge Nhiều File PDF
from PyPDF2 import PdfMerger
import glob
merger = PdfMerger()
# Gộp tất cả PDF trong folder, theo thứ tự tên
for pdf in sorted(glob.glob("C:/HopDong/*.pdf")):
merger.append(pdf)
print(f"+ {pdf}")
merger.write("TongHop_HopDong.pdf")
merger.close()
print("✅ Merged!")Script 5: PDF Sang Excel (Extract Tables)
import tabula # pip install tabula-py
# Trích xuất bảng từ PDF
tables = tabula.read_pdf("BaoCaoTC.pdf", pages="all")
# Mỗi bảng là 1 DataFrame
for i, table in enumerate(tables):
table.to_excel(f"Bang_{i+1}.xlsx", index=False)
print(f"Table {i+1}: {table.shape}")Script 6: Web Scraping — Lấy Dữ Liệu Từ Website
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = "https://example.com/bang-gia"
resp = requests.get(url)
soup = BeautifulSoup(resp.text, "html.parser")
# Tìm bảng HTML
table = soup.find("table")
rows = []
for tr in table.find_all("tr"):
cells = [td.text.strip() for td in tr.find_all(["td", "th"])]
rows.append(cells)
df = pd.DataFrame(rows[1:], columns=rows[0])
df.to_excel("BangGia.xlsx", index=False)
print(f"Scraped {len(df)} dòng")Script 7: Tạo Báo Cáo Excel Có Format
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
# Tạo DataFrame
df = pd.read_excel("DuLieu.xlsx")
summary = df.groupby("PhongBan").agg(
SoNV=("HoTen", "count"),
TongLuong=("Luong", "sum"),
LuongTB=("Luong", "mean")
).round(0)
# Xuất ra Excel
summary.to_excel("BaoCao.xlsx", sheet_name="TongHop")
# Format với openpyxl
wb = load_workbook("BaoCao.xlsx")
ws = wb.active
# Header style
header_fill = PatternFill(start_color="1F4E79", fill_type="solid")
header_font = Font(color="FFFFFF", bold=True, size=12)
for cell in ws[1]:
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal="center")
# Number format cho cột tiền
for row in ws.iter_rows(min_row=2, min_col=3, max_col=4):
for cell in row:
cell.number_format = "#,##0"
# Auto-fit column width
for col in ws.columns:
max_len = max(len(str(c.value or "")) for c in col)
ws.column_dimensions[get_column_letter(col[0].column)].width = max_len + 3
wb.save("BaoCao.xlsx")
print("✅ Report created with formatting!")Script 8: Theo Dõi Thay Đổi Giá (Price Monitoring)
import requests
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
import os
def check_price(url, selector):
resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(resp.text, "html.parser")
price_elem = soup.select_one(selector)
if price_elem:
price = price_elem.text.strip()
return price
return None
# Danh sách sản phẩm cần theo dõi
products = [
{"name": "Laptop ABC", "url": "https://...", "selector": ".product-price"},
{"name": "Phone XYZ", "url": "https://...", "selector": ".price"},
]
# Thu thập giá
results = []
for p in products:
price = check_price(p["url"], p["selector"])
results.append({
"Thời gian": datetime.now().strftime("%Y-%m-%d %H:%M"),
"Sản phẩm": p["name"],
"Giá": price
})
# Lưu vào file (append)
df_new = pd.DataFrame(results)
if os.path.exists("GiaTheoNgay.xlsx"):
df_old = pd.read_excel("GiaTheoNgay.xlsx")
df = pd.concat([df_old, df_new], ignore_index=True)
else:
df = df_new
df.to_excel("GiaTheoNgay.xlsx", index=False)
print(f"✅ Tracked {len(results)} products")Cách Chạy Script Python
Cài Python: python.org → Download → cài đặt (tick Add to PATH)
Cài thư viện: mở CMD → pip install pandas openpyxl requests beautifulsoup4 PyPDF2
Lưu script: tạo file .py (VD: gop_file.py)
Chạy: mở CMD → python gop_file.py
Tự động: dùng Task Scheduler chạy python script.py hàng ngày
Kết Luận
8 script trên cover 80% nhu cầu tự động hóa văn phòng. Python không khó — bạn chỉ cần copy script, sửa đường dẫn/tên file, và chạy. Dần dần bạn sẽ hiểu logic và tự viết được script riêng.
Học thêm Python cho dân văn phòng tại Trà Đá Data! 🍵
Bình luận
Đăng nhập để tham gia bình luận
Đăng nhậpNhận bài viết mới nhất
Đăng ký để nhận thông báo khi có bài viết mới. Không spam, chỉ kiến thức chất lượng.
Bài viết liên quan
Khám phá thêm các bài viết cùng chủ đề

