Analyzing Automation Needs
I'm focused on grasping the essence of the user's need: automating Excel report creation with Python and openpyxl. The core idea revolves around transforming raw data into a structured format without manual effort. I'm prioritizing the steps needed to convert raw data into a nicely formatted and easy to read Excel report, and trying to focus on the key components to achieve this.
Deconstructing Report Elements
I'm now dissecting the core elements of the report generation process, specifically the required formatting aspects. I'm focusing on the practical application of openpyxl's features. This involves how to create bold headers, apply currency formatting, and adjust column widths for optimal readability. I'm thinking through how to structure the Python code to manage this seamlessly.
Formulating Code Structure
I'm translating the implementation plan into executable code. The key is now crafting a modular structure to ease maintenance and reusability, with dedicated functions for data preparation, workbook initialization, header creation, data writing, formatting, formula application, and charting. I'm focusing on defining function signatures and parameter passing. I'm also planning error handling for the code.
Creating Report Blueprint
I'm now in the process of formulating a detailed, step-by-step implementation plan. I'm focusing on key aspects such as initial setup with import statements, data handling (both dummy and potential Pandas integration), the creation of a workbook and worksheet, header formatting, and the addition of formulas and charts to complete the report structure. The plan is to create a complete and functional code, ready to be deployed.
Structuring the Implementation
I'm now consolidating the plan. This includes organizing the different blocks of code. I'm focusing on incorporating the pandas integration, and how I'm going to present it to the user. I'm also considering the "Pro Tip" section on pandas. I'm finalizing the structure of the final output now, to ensure clarity and usability.
Here is a comprehensive, step-by-step Python script to generate an automated Excel report using the openpyxl library.
This script goes beyond just writing data; it includes styling, formulas, conditional formatting, and charts to create a professional-looking report.
Prerequisites
First, ensure you have the library installed:
pip install openpyxl
The Python Script
Save this code as generate_report.py and run it.
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.chart import BarChart, Reference
from openpyxl.utils import get_column_letter
def create_sales_report(filename="Sales_Report.xlsx"):
# 1. Setup Data (Simulating a Database Query)
data = [
["Product", "Region", "Price", "Units Sold"], # Header
["Widget A", "North", 12.50, 450],
["Widget A", "South", 12.50, 300],
["Gadget B", "North", 45.00, 120],
["Gadget B", "South", 45.00, 200],
["Gizmo C", "North", 85.00, 50],
["Gizmo C", "South", 85.00, 80],
]
# 2. Initialize Workbook and Worksheet
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Q1 Sales Summary"
# 3. Write Data to Sheet
for row in data:
ws.append(row)
# 4. Define Styles
# Header Style: Bold, White Text, Blue Background
header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill("solid", fgColor="4F81BD")
header_alignment = Alignment(horizontal="center", vertical="center")
# Border Style
thin_border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
# 5. Apply Header Styles
for cell in ws[1]:
cell.font = header_font
cell.fill = header_fill
cell.alignment = header_alignment
cell.border = thin_border
# 6. Add Content Logic (Formulas and Currencies)
# We start loop at index 2 because Excel row 1 is headers
# We calculate Total Revenue (Price * Units) in a new Column E
ws["E1"] = "Total Revenue" # Add Header for new column
ws["E1"].font = header_font
ws["E1"].fill = header_fill
ws["E1"].alignment = header_alignment
ws["E1"].border = thin_border
last_row = len(data)
for row_num in range(2, last_row + 1):
# Write Formula: =C2*D2
price_cell = f"C{row_num}"
units_cell = f"D{row_num}"
ws[f"E{row_num}"] = f"={price_cell}*{units_cell}"
# Format Price and Total Revenue columns as Currency
ws[f"C{row_num}"].number_format = '$#,##0.00'
ws[f"E{row_num}"].number_format = '$#,##0.00'
# Apply borders to all data cells
for col_num in range(1, 6): # Columns A to E
cell = ws.cell(row=row_num, column=col_num)
cell.border = thin_border
# 7. Add Grand Total Row
total_row = last_row + 1
ws[f"D{total_row}"] = "GRAND TOTAL:"
ws[f"D{total_row}"].font = Font(bold=True)
ws[f"D{total_row}"].alignment = Alignment(horizontal="right")
# Formula: SUM(E2:E7)
ws[f"E{total_row}"] = f"=SUM(E2:E{last_row})"
ws[f"E{total_row}"].font = Font(bold=True)
ws[f"E{total_row}"].number_format = '$#,##0.00'
# 8. Auto-adjust Column Widths
for col_idx, col_cells in enumerate(ws.columns, 1):
max_length = 0
column = get_column_letter(col_idx)
for cell in col_cells:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2)
ws.column_dimensions[column].width = adjusted_width
# 9. Generate a Bar Chart
chart = BarChart()
chart.type = "col"
chart.style = 10
chart.title = "Revenue by Transaction"
chart.y_axis.title = 'Revenue'
chart.x_axis.title = 'Transaction ID'
# Data for chart (The computed 'Total Revenue' column)
data_ref = Reference(ws, min_col=5, min_row=1, max_row=last_row, max_col=5)
# Categories for chart (The Product Names)
cats_ref = Reference(ws, min_col=1, min_row=2, max_row=last_row)
chart.add_data(data_ref, titles_from_data=True)
chart.set_categories(cats_ref)
# Place chart starting at cell G2
ws.add_chart(chart, "G2")
# 10. Save File
wb.save(filename)
print(f"Success! Report saved as {filename}")
if __name__ == "__main__":
create_sales_report()
Key Features Explained
-
Writing Formulas (ws[cell] = "=...")
We didn't hardcode the total revenue; we wrote an Excel formula (e.g., =C2*D2). This creates a dynamic sheet where, if you open the file and change the quantity manually, the total updates automatically.
-
Styling (openpyxl.styles)
Raw Excel dumps are hard to read. We created PatternFill object for background colors and Font objects for bold text. We applied these to the header row specifically to separate it from the data.
-
Number Formats
using cell.number_format = '$#,##0.00', we ensure that prices look like currency ($12.50) rather than raw floats (12.5) inside Excel.
-
Auto-Adjusting Widths
Section #8 iterates through every column, checks the length of the longest string in that column, and adjusts the width so the text doesn't get cut off.
-
Charts (openpyxl.chart)
We generated a native Excel chart.
- Reference Objects: These tell Excel where the data is.
add_chart: This places the chart object onto the sheet canvas.
Alternative: Using Pandas (Recommended for large data)
If you are dealing with thousands of rows, calculating data in Python using Pandas is often faster and easier, though pure openpyxl gives you more control over styling.
Here is how you would do the data processing part with Pandas, then output to Excel:
import pandas as pd
# 1. Create DataFrame
df = pd.DataFrame({
'Product': ["Widget A", "Widget A", "Gadget B"],
'Price': [12.50, 12.50, 45.00],
'Units': [450, 300, 120]
})
# 2. Calculate in Python
df['Total Revenue'] = df['Price'] * df['Units']
# 3. Export to Excel
df.to_excel("Pandas_Report.xlsx", index=False, sheet_name="Sales Q1")