Tự Động Hóa Báo Cáo Excel Bằng Python: Openpyxl Và XlsxWriter
Chia sẻ
"Hướng dẫn dùng Python để tự động tạo báo cáo Excel định kỳ: đọc dữ liệu, xử lý, tạo chart và format chuyên nghiệp. Tiết kiệm hàng giờ mỗi tuần."
1. Tại Sao Tự Động Hóa Báo Cáo Bằng Python?
Mỗi tuần/tháng, dân Data phải tạo báo cáo Excel: copy data, format bảng, vẽ chart, gửi email. Công việc lặp đi lặp lại này hoàn toàn có thể tự động hóa bằng Python. Chỉ cần viết script 1 lần, chạy tự động mãi mãi.
Hai thư viện phổ biến nhất: Openpyxl (đọc/ghi .xlsx, giữ nguyên formatting) và XlsxWriter (tạo file mới với chart, conditional formatting đẹp). Bài viết này hướng dẫn cả hai từ cơ bản đến nâng cao.
2. Cài Đặt Và Import
pip install openpyxl xlsxwriter pandas
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.chart import BarChart, Reference
import xlsxwriter
import pandas as pdOpenpyxl phù hợp khi cần sửa file Excel có sẵn (giữ nguyên format, macro). XlsxWriter phù hợp khi tạo file mới từ đầu với chart và format phức tạp.
3. Openpyxl: Đọc Và Ghi File Excel
# Đọc file có sẵn
wb = openpyxl.load_workbook("report_template.xlsx")
ws = wb.active
# Ghi dữ liệu
ws["A1"] = "Báo Cáo Doanh Thu"
ws["A1"].font = Font(name="Arial", size=16, bold=True, color="003366")
ws["A1"].fill = PatternFill(start_color="E6F3FF", fill_type="solid")
# Ghi hàng loạt từ Pandas DataFrame
df = pd.read_sql("SELECT * FROM sales", conn)
for r_idx, row in enumerate(df.itertuples(index=False), start=3):
for c_idx, value in enumerate(row, start=1):
ws.cell(row=r_idx, column=c_idx, value=value)
wb.save("report_output.xlsx")Lưu ý: Openpyxl không hỗ trợ file .xls (chỉ .xlsx). Nếu cần đọc .xls, dùng xlrd. Openpyxl cũng không chạy macro — chỉ giữ nguyên macro có sẵn.
4. Openpyxl: Tạo Chart Tự Động
# Tạo Bar Chart tự động
chart = BarChart()
chart.title = "Doanh Thu Theo Tháng"
chart.y_axis.title = "VND"
chart.x_axis.title = "Tháng"
data = Reference(ws, min_col=2, min_row=2, max_row=13, max_col=2)
cats = Reference(ws, min_col=1, min_row=3, max_row=13)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.shape = 4 # Bar style
ws.add_chart(chart, "D2") # Đặt chart tại D2
wb.save("report_with_chart.xlsx")5. XlsxWriter: Format Chuyên Nghiệp
workbook = xlsxwriter.Workbook("sales_report.xlsx")
ws = workbook.add_worksheet("Report")
# Định nghĩa format
header_fmt = workbook.add_format({
"bold": True, "font_color": "white",
"bg_color": "#2B579A", "border": 1,
"align": "center", "font_size": 12
})
money_fmt = workbook.add_format({"num_format": "#,##0 ₫", "border": 1})
# Ghi headers
headers = ["Tháng", "Doanh Thu", "Chi Phí", "Lợi Nhuận"]
for col, h in enumerate(headers):
ws.write(0, col, h, header_fmt)
# Conditional formatting: highlight số âm
ws.conditional_format("D2:D13", {
"type": "cell", "criteria": "<", "value": 0,
"format": workbook.add_format({"font_color": "red", "bold": True})
})
workbook.close()6. Tích Hợp Pandas + Gửi Email Tự Động
Kết hợp Pandas query database, tạo báo cáo Excel, rồi gửi qua email bằng smtplib — hoàn toàn tự động, có thể chạy bằng cron job hoặc Task Scheduler.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
def send_report(file_path, to_email):
msg = MIMEMultipart()
msg["Subject"] = f"Báo Cáo Tuần {datetime.now().strftime("%d/%m/%Y")}"
with open(file_path, "rb") as f:
part = MIMEBase("application", "octet-stream")
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename={file_path}")
msg.attach(part)
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login(email, password)
server.send_message(msg)7. Best Practices Và Mẹo
Luôn dùng context manager (with) khi mở file. Validate dữ liệu trước khi ghi. Dùng logging thay print để debug. Tách logic thành functions riêng biệt. Lưu template và output ở thư mục khác nhau để tránh ghi đè.
Openpyxl xử lý tốt file ≤ 50MB. Với file lớn hơn, dùng openpyxl.load_workbook(read_only=True) hoặc chuyển sang pandas.read_excel(engine="openpyxl") để tiết kiệm RAM.
8. Kết Luận
Python + Openpyxl/XlsxWriter là bộ đôi hoàn hảo để tự động hóa báo cáo Excel. Từ query database, xử lý dữ liệu, tạo chart, format bảng đến gửi email — tất cả chỉ trong 1 script. Hãy bắt đầu với 1 báo cáo đơn giản rồi mở rộng dần.
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ủ đề


