The user wants a Python script to automate Excel report generation using the openpyxl library.
1. Understand the Goal:
The goal is to create a script that:
- Reads data (simulated or from a file).
- Creates an Excel workbook.
- Adds data to a worksheet.
- Applies formatting (headers, numbers, etc.).
- Adds charts.
- Saves the file.
2. Identify the Key Library:
openpyxl is the standard library for reading/writing Excel 2010 xlsx/xlsm files in Python.
3. Determine the Steps:
- Import necessary modules:
Workbook, styles, chart classes.
- Create Data: Need some sample data to make the report meaningful. Let's use sales data (Product, Sales, Cost).
- Initialize Workbook: Create a
Workbook object and grab the active sheet.
- Write Headers: Put column names in the first row.
- Write Data: Loop through the data and populate the cells.
- Apply Formatting:
- Header styling (Bold, Fill color).
- Column width adjustment (important for readability).
- Number formatting (currency).
- Add Formulas: (Optional but good for "reports") Add a Total row or Profit column. Let's add a Profit column.
- Add Charts: A bar chart or pie chart is standard. Let's do a Bar chart for Sales vs Profit.
- Save: Save the
.xlsx file.
4. Draft the Code (Mental or Scratchpad):
- Imports:
from openpyxl import Workbook, from openpyxl.styles import Font, Alignment, PatternFill, from openpyxl.chart import BarChart, Reference.
- Data: A list of lists or dictionaries.
data = [("Product A", 100, 50), ...]
- Setup:
wb = Workbook(), ws = wb.active.
- Headers:
ws.append(["Product", "Sales", "Cost", "Profit"]).
- Styling: Define a header font and fill. Apply to row 1.
- Writing Data: Loop and
ws.append. Calculate profit inside the loop? Or write formula? Writing the formula =B2-C2 is more "Excel-like" and dynamic. Let's write formulas.
- Formatting Data: Loop through columns B and C to set number format to
$#,##0.00.
- Chart:
chart = BarChart().
data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=... ).
cats = Reference(ws, min_col=1, min_row=2, max_row=... ).
chart.add_data(data, titles_from_data=True).
chart.set_categories(cats).
ws.add_chart(chart, "E2").
5. Refine and Polish:
- Add comments to explain what the code does.
- Make sure error handling is minimal but valid (file permissions).
- Add a "Requirements" section so the user knows to
pip install openpyxl.
6. Construct the Final Output:
- Title: Python Script for Automated Excel Reports.
- Prerequisites: Mention
pip install openpyxl.
- The Code: Write clean, well-commented Python code.
- Explanation: Break down the key parts (Setup, Data, Styling, Charts).
- Advanced Tips: Mention things like Pivot Tables (not fully supported in openpyxl creation), conditional formatting, or locking cells.
Self-Correction during drafting:
- Initial thought: Just dump data. Correction: A "report" implies formatting. I must include styling (colors, fonts) to make it a real report example.
- Initial thought: Use
pandas. Correction: The prompt specifically asked for openpyxl. While pandas can use openpyxl as an engine, using pure openpyxl gives more control over specific cell formatting and chart objects, which is usually what "report generation" entails. I will stick to pure openpyxl.
Final Code Structure:
- Imports.
- Sample Data definition.
- Function
generate_report(filename).
- Inside function:
- Create Workbook.
- Write Headers & Style them.
- Write Data & Formulas.
- Auto-adjust column widths.
- Create Chart.
- Save.
Let's write the code.
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.chart import BarChart, Reference
# ... code ...
Looks good. I will present this clearly.
Here is a complete, step-by-step Python script to automate Excel report generation using openpyxl.
This script covers the most common requirements: creating a workbook, formatting headers, writing data, applying formulas, and generating a chart.
Prerequisites
You need to install the openpyxl library if you haven't already:
pip install openpyxl
The Python Script
Save this code as generate_report.py.
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.chart import BarChart, Reference
from openpyxl.utils import get_column_letter
import datetime
def create_sales_report(filename="sales_report.xlsx"):
# 1. Create a Workbook and select the active sheet
wb = Workbook()
ws = wb.active
ws.title = "Sales Report"
# 2. Define Dummy Data
# Format: [Product, Units Sold, Unit Price]
data = [
["Product", "Units Sold", "Unit Price", "Total Revenue"],
["Laptop", 12, 999.99],
["Smartphone", 45, 699.50],
["Tablet", 20, 350.00],
["Monitor", 8, 199.99],
["Keyboard", 50, 45.00],
]
# 3. Write Data to Sheet
# We start from row 1, col 1 (top left)
start_row = 1
for row_idx, row_data in enumerate(data, start=start_row):
for col_idx, value in enumerate(row_data, start=1):
ws.cell(row=row_idx, column=col_idx, value=value)
# 4. Apply Styling to the Header Row
# Define styles
header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill(start_color="4F81BD", end_color="4F81BD", fill_type="solid")
center_align = Alignment(horizontal="center", vertical="center")
# Loop through the header row (row 1) and apply styles
for col in range(1, 5):
cell = ws.cell(row=start_row, column=col)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center_align
# 5. Add Formulas
# Calculate Total Revenue (Units * Price) for rows 2 to 6
# Excel formula: =B2*C2
for row in range(start_row + 1, start_row + len(data)):
# We are writing the formula into the 4th column (D)
ws.cell(row=row, column=4, value=f"=B{row}*C{row}")
# Format the currency columns (C and D)
ws.cell(row=row, column=3).number_format = '$#,##0.00'
ws.cell(row=row, column=4).number_format = '$#,##0.00'
# 6. Add Borders to all data cells
thin_border = Border(
left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin')
)
for row in ws.iter_rows(min_row=start_row, max_row=start_row + len(data)-1, min_col=1, max_col=4):
for cell in row:
cell.border = thin_border
# 7. Adjust Column Widths
# Auto-adjust is not native in openpyxl, so we manually set reasonable widths
ws.column_dimensions['A'].width = 15
ws.column_dimensions['B'].width = 12
ws.column_dimensions['C'].width = 12
ws.column_dimensions['D'].width = 15
# 8. Add a Chart
chart = BarChart()
chart.type = "col" # Vertical bars
chart.style = 10
chart.title = "Revenue by Product"
chart.y_axis.title = 'Revenue ($)'
chart.x_axis.title = 'Product'
# Define data for the chart (Total Revenue)
# Data includes headers (titles_from_data=True)
data_ref = Reference(ws, min_col=4, min_row=1, max_row=6, max_col=4)
# Define categories (Product Names)
cats_ref = Reference(ws, min_col=1, min_row=2, max_row=6)
chart.add_data(data_ref, titles_from_data=True)
chart.set_categories(cats_ref)
chart.shape = 4
# Position the chart (E2 is top left corner of chart)
ws.add_chart(chart, "E2")
# 9. Save the File
wb.save(filename)
print(f"Report generated successfully: {filename}")
if __name__ == "__main__":
# Create a timestamped filename
today = datetime.date.today()
filename = f"Sales_Report_{today}.xlsx"
create_sales_report(filename)
Key Features Explained
- Styling (
openpyxl.styles):
- We create objects for
Font, PatternFill, and Alignment.
- We apply these to specific cells (like the header row) to make the report look professional.
- Formulas:
- Instead of calculating the total in Python, we write a string
=B{row}*C{row} into the cell. This allows the Excel user to change the numbers later, and the total will update automatically.
- Number Formatting:
- We used
.number_format = '$#,##0.00' so Excel knows these are currency fields.
- Charts (
openpyxl.chart):
- We use
Reference to tell Excel exactly which cells contain the data (Revenue) and which contain the labels (Products).
- Dynamic File Naming:
- The script uses
datetime to save a unique file every day (e.g., Sales_Report_2023-10-27.xlsx).
How to Run It
Run the script from your terminal:
python generate_report.py
Check your folder for the new .xlsx file. Open it to see the formatted data and the generated chart.