File & Media Automation
Excel is the universal language of business. The openpyxl package allows Python scripts to read, modify, format, apply Excel formulas, and generate automated financial workbooks without installing Microsoft Office.
The openpyxl Hierarchy:
- Workbook: The entire
.xlsxfile in memory. - Worksheet (Sheet): A specific tab within the workbook (e.g.
wb['Q1_Sales']). - Cell: An individual coordinate (e.g.
sheet['B4']orsheet.cell(row=4, column=2)) holding values, formulas (=SUM(B2:B10)), and font formatting.
# Excel Automation Simulation: Generating an Automated Financial Report
def generate_excel_financial_report(sales_data):
"""Simulates openpyxl workbook creation and formula computation."""
workbook = {"title": "Q3_Financial_Summary.xlsx", "rows": []}
# 1. Header row:
headers = ["Transaction ID", "Client Name", "Product", "Gross Amount (INR)", "GST (18%)", "Total Payable"]
workbook["rows"].append(headers)
# 2. Populate transaction rows with automated formula calculation:
for idx, (client, product, gross) in enumerate(sales_data, start=1001):
gst = round(gross * 0.18, 2)
total = round(gross + gst, 2)
workbook["rows"].append([f"INV#{idx}", client, product, f"โน{gross:,.2f}", f"โน{gst:,.2f}", f"โน{total:,.2f}"])
return workbook
sample_sales = [
("TechCorp India", "Cloud Enterprise License", 150000.0),
("Apex Dynamics", "Cybersecurity Audit", 85000.0),
("InnovateLabs", "AI Training Platform", 220000.0)
]
report = generate_excel_financial_report(sample_sales)
print(f"--- ๐ Automated Excel Workbook Generated: [{report['title']}] ---")
for r in report["rows"]:
print(f"{r[0]:<10} {r[1]:<18} {r[2]:<26} {r[3]:<16} {r[4]:<12} {r[5]:<14}")
In openpyxl: import openpyxl; wb = openpyxl.Workbook(); ws = wb.active; ws.append(['Name', 'Sales']); ws['B5'] = '=SUM(B2:B4)'; wb.save('report.xlsx').
Python provides mature standard libraries and third-party packages for complete media pipeline automation:
- PDF Processing (
pypdf/pdfplumber): Extract text from contracts, merge multiple PDF files, rotate pages, and encrypt documents with passwords. - Image Processing (
Pillow / PIL): Batch resize photos, crop banners, apply watermarks, convert PNG to WebP/JPEG, and compress images for web publishing. - Email Automation (
smtplib&email.mime): Connects to SMTP servers (Gmail, SendGrid, Amazon SES) to send automated transactional HTML emails with PDF invoice attachments.
# Automated Email Dispatch Pipeline Simulation:
import datetime
class AutomatedEmailDispatcher:
"""Simulates sending rich HTML emails with attachments via SMTP."""
def __init__(self, smtp_server="smtp.gmail.com", port=587):
self.server = smtp_server
self.port = port
def send_invoice_email(self, recipient_email, customer_name, invoice_id, amount, attachment_file):
"""Constructs MIME multipart message and sends via SMTP."""
email_payload = {
"To": recipient_email,
"From": "billing@ourcompiler.com",
"Subject": f"Invoice #{invoice_id} from Our Compiler โ Paid Successfully",
"Date": datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S"),
"Attachment": attachment_file,
"HTML_Body": f"""
Dear {customer_name},
Thank you for your business! Your payment of โน{amount:,.2f} has been processed successfully.
Your official tax invoice {attachment_file} is attached to this email.
Best regards,
Our Compiler Billing Team
"""
}
print(f"๐ง [SMTP DISPATCH] Sent Email to {recipient_email} with attachment: '{attachment_file}'")
return email_payload
# Run Email Dispatcher Demo:
dispatcher = AutomatedEmailDispatcher()
res = dispatcher.send_invoice_email(
recipient_email="balaji.dev@example.com",
customer_name="Balaji",
invoice_id="INV-2026-894",
amount=1499.00,
attachment_file="Invoice_INV-2026-894.pdf"
)
In production Python, use server = smtplib.SMTP('smtp.gmail.com', 587); server.starttls() to encrypt credentials with Transport Layer Security (TLS) before sending passwords.
Never write raw email passwords in Python code. When using Gmail, generate an App Password from Google Security settings and load it via os.getenv("EMAIL_APP_PASSWORD").
Write an image thumbnail calculator function get_thumbnail_size(width, height, max_size=300) that maintains the original aspect ratio.
def get_thumbnail_size(width, height, max_size=300):
ratio = min(max_size / width, max_size / height)
return int(width * ratio), int(height * ratio)
print("Original 1920x1080 -> Thumbnail:", get_thumbnail_size(1920, 1080))
print("Original 800x1200 -> Thumbnail:", get_thumbnail_size(800, 1200))
Q Which library is best for extracting tables from PDFs in Python?
pdfplumber is the gold standard for extracting complex tabular data from PDF files, while pypdf is optimal for merging, splitting, and rotating PDF pages.
Q How do I convert an image format from PNG to WebP in Pillow?
Open with img = Image.open("photo.png") and save with img.save("photo.webp", "WEBP", quality=85, optimize=True).
Q What is the difference between openpyxl and Pandas for Excel files?
Pandas (pd.read_excel) is optimized for loading tabular numeric data into DataFrames for analysis. openpyxl is designed for cell-level formatting, styling, charts, and formulas.