The user wants a Python script to automate Excel report generation.
This is a broad request. I need to provide a comprehensive, reusable, and easy-to-understand example.
Key components of Excel report automation:
- Data Source: Where is the data coming from? (CSV, database, dummy data for the example). I'll use dummy data created with
pandas for simplicity and portability.
- Data Manipulation: Processing the data (grouping, calculating sums/averages).
pandas is the standard tool here.
- Excel Writing: Writing to an Excel file.
openpyxl or xlsxwriter are the best engines to use with pandas for formatting.
- Formatting/Visualization: Making it look like a "report" (bold headers, auto-column width, charts, conditional formatting).
- Structure: I should create a script that does the following:
- Generates sample data.
- Performs some analysis (pivot tables).
- Writes the raw data and the analysis to separate sheets.
- Applies formatting (headers, number formatting).
- Adds a simple chart.
Step-by-Step Plan:
- Prerequisites: Mention necessary libraries (
pandas, openpyxl, xlsxwriter).
- The Script:
- Import libraries.
- Create a function to generate dummy data (Sales data is a classic example).
- Create a function to process data (e.g., Sales by Region, Monthly Sales).
- Create the main generation function using
xlsxwriter as the engine because it has robust charting and formatting features compared to openpyxl when used via Pandas.
- Detailed Logic within the main function:
- Create a Pandas Excel writer using
xlsxwriter.
- Write the raw data to Sheet 1.
- Create a summary/pivot table and write it to Sheet 2.
- Access the
xlsxwriter workbook and worksheet objects to apply formatting (bold headers, borders).
- Add a chart based on the summary data.
- Save the file.
- Explanation: Briefly explain what each part does.
- Customization: Give tips on how to adapt it (connecting to SQL, adding more complex logic).
Drafting the Code (Mental or scratchpad):
- Imports:
pandas, datetime, random.
- Data: List of dictionaries or a DataFrame constructor. Let's use a DataFrame with columns: Date, Region, Product, Amount.
- Analysis:
groupby(['Region'])['Amount'].sum().
- Writing:
pd.ExcelWriter('report.xlsx', engine='xlsxwriter').
- Formatting: Get
writer.book and writer.sheets. Define formats (book.add_format). Write headers separately or use df.to_excel(header=True). Self-correction: df.to_excel is easier, but adjusting column width requires accessing the underlying worksheet object and iterating.
Refining the Output:
I will provide a complete, copy-pasteable script. I will focus on xlsxwriter because it's generally faster and better for creating new reports with charts than openpyxl, though both are good.
Structure of the response:
- Introduction: Brief overview.
- Requirements:
pip install pandas xlsxwriter.
- The Code: A single, well-commented Python block.
- Breakdown: Explanation of the data creation, the pivot table, the Excel writer, and the formatting.
- Next Steps: How to make it scheduled or read real data.
Let's write the code.
- Function
create_dummy_data: Returns a DataFrame.
- Function
process_data: Returns a summary DataFrame (e.g., Sales by Product).
- Function
generate_report:
writer = pd.ExcelWriter(...)
- Write raw data.
- Write summary.
- Get
workbook and worksheet objects.
- Add chart.
- Format columns (autofit logic isn't built-in to xlsxwriter easily, but I can write a helper loop to set width based on max length).
- Close writer.
This looks solid. I will implement a "Sales Report" scenario as it covers most common use cases (dates, categories, numbers).
Self-Correction during drafting: The autofit logic in xlsxwriter isn't automatic. I'll add a small helper function to calculate column widths based on the header length or data content length to make it look professional.
Let's proceed.
Here is a complete, robust Python script to automate Excel report generation.
This script uses Pandas for data analysis and XlsxWriter to create a professional Excel file with custom formatting, charts, and an autofilter.
Prerequisites
You will need to install the necessary libraries via terminal/command prompt:
pip install pandas xlsxwriter
The Python Script
Save this code as generate_report.py.
import pandas as pd
import random
from datetime import datetime, timedelta
def create_dummy_data():
"""
Generates dummy sales data for the report.
In a real scenario, you would read this from a CSV or Database.
"""
print("Generating dummy data...")
data = []
start_date = datetime(2023, 1, 1)
for i in range(100):
date = start_date + timedelta(days=random.randint(0, 180))
region = random.choice(['North', 'South', 'East', 'West'])
product = random.choice(['Widget A', 'Widget B', 'Gadget X', 'Gadget Y'])
units = random.randint(10, 100)
unit_cost = random.randint(20, 50)
total = units * unit_cost
data.append([date, region, product, units, unit_cost, total])
df = pd.DataFrame(data, columns=['Date', 'Region', 'Product', 'Units Sold', 'Unit Cost', 'Total Revenue'])
return df
def generate_excel_report(df, output_filename):
"""
Generates a formatted Excel report with a data sheet,
a summary sheet, and a chart.
"""
print(f"Writing report to {output_filename}...")
# Create a Pandas Excel writer using XlsxWriter as the engine
writer = pd.ExcelWriter(output_filename, engine='xlsxwriter')
# ------------------------------------------------------------------
# 1. RAW DATA SHEET
# ------------------------------------------------------------------
sheet_name_data = 'Transaction Data'
df.to_excel(writer, sheet_name=sheet_name_data, index=False)
# Get the xlsxwriter workbook and worksheet objects
workbook = writer.book
worksheet_data = writer.sheets[sheet_name_data]
# Apply formatting
# Create a format for the header
header_format = workbook.add_format({
'bold': True,
'text_wrap': True,
'valign': 'top',
'fg_color': '#4F81BD',
'font_color': 'white',
'border': 1
})
# Write the column headers with the defined format
for col_num, value in enumerate(df.columns.values):
worksheet_data.write(0, col_num, value, header_format)
# Set column widths
worksheet_data.set_column('A:A', 12) # Date
worksheet_data.set_column('B:F', 15) # Others
# Add a filter to the headers
worksheet_data.autofilter(0, 0, len(df), len(df.columns) - 1)
# Freeze the top row
worksheet_data.freeze_panes(1, 0)
# ------------------------------------------------------------------
# 2. SUMMARY PIVOT TABLE SHEET
# ------------------------------------------------------------------
sheet_name_summary = 'Summary'
# Create a pivot table (e.g., Total Revenue by Region)
pivot_df = df.pivot_table(
index='Region',
values='Total Revenue',
aggfunc='sum'
).reset_index()
# Write the pivot table to the summary sheet
pivot_df.to_excel(writer, sheet_name=sheet_name_summary, index=False, startrow=2)
worksheet_summary = writer.sheets[sheet_name_summary]
# Add a title to the summary sheet
title_format = workbook.add_format({'bold': True, 'font_size': 16})
worksheet_summary.write(0, 0, 'Sales Report Summary', title_format)
# Format the pivot table headers
for col_num, value in enumerate(pivot_df.columns.values):
worksheet_summary.write(2, col_num, value, header_format)
# Set currency format for the revenue column
currency_format = workbook.add_format({'num_format': '$#,##0.00'})
worksheet_summary.set_column('B:B', 18, currency_format)
# ------------------------------------------------------------------
# 3. CHART CREATION
# ------------------------------------------------------------------
# Create a bar chart
chart = workbook.add_chart({'type': 'column'})
# Configure the series. Note: XlsxWriter uses 0-based indexing.
# Categories (Region) are in column A (0), row 3 to len(pivot)+2
# Values (Revenue) are in column B (1)
chart.add_series({
'name': 'Total Revenue',
'categories': [sheet_name_summary, 3, 0, len(pivot_df)+2, 0],
'values': [sheet_name_summary, 3, 1, len(pivot_df)+2, 1],
'fill': {'color': '#4F81BD'},
})
# Set chart title and axis labels
chart.set_title({'name': 'Revenue by Region'})
chart.set_x_axis({'name': 'Region'})
chart.set_y_axis({'name': 'Revenue ($)'})
# Insert the chart into the summary sheet
worksheet_summary.insert_chart('D2', chart, {'x_offset': 25, 'y_offset': 10})
# ------------------------------------------------------------------
# 4. FINALIZE
# ------------------------------------------------------------------
writer.close()
print("Report generated successfully!")
if __name__ == "__main__":
# 1. Get Data
data_frame = create_dummy_data()
# 2. Define output filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"Sales_Report_{timestamp}.xlsx"
# 3. Generate Report
generate_excel_report(data_frame, filename)
Key Features of this Script:
- Separation of Concerns: It separates data generation (or fetching) from the Excel writing logic.
- Formatting: It doesn't just dump raw text. It applies:
- Header Formatting: Blue background with white bold text.
- Number Formatting: Currency symbols for money columns.
- Column Widths: Adjusts columns so text fits.
- User Experience:
- Freeze Panes: Freezes the header row so it stays visible when you scroll down.
- Autofilter: Adds the little dropdown arrows to headers for easy sorting/filtering.
- Data Analysis: It uses
pivot_table to automatically summarize raw transaction data into a "Summary" sheet.
- Visualization: It automatically generates a Column Chart based on the summary data and embeds it in the Excel file.
How to customize this:
- Connecting a Database: Replace the
create_dummy_data() function with pd.read_sql("SELECT * FROM sales", connection_string).
- Reading a CSV: Replace it with
pd.read_csv("input_data.csv").
- Conditional Formatting: You can use
worksheet.conditional_format() to highlight low values in red or high values in green.