Chapter 7: Case Study - Automating a Monthly Sales Report
Congratulations on making it this far! It's time to put all your skills together to tackle a real-world scenario. In this chapter, we will build a single Python script that automates the entire process of creating a professional monthly sales report.
The Goal
Our objective is to write a script that takes a raw CSV (Comma-Separated Values) file of sales data, processes it, and generates a polished, multi-sheet Excel report complete with a summary, formatted data, and a chart for visualization.
The Raw Data: sales_data.csv
sales_data.csvFirst, you'll need some raw data. Create a file named sales_data.csv and paste the following content into it. This is a common format for exporting data from databases or other systems.
Product,Category,Price,Units Sold
Laptop,Electronics,1200,15
Mouse,Electronics,25,150
Keyboard,Electronics,75,80
Monitor,Electronics,300,45
Webcam,Electronics,50,100
Desk Chair,Furniture,250,30
Office Desk,Furniture,400,20
Pen Holder,Office Supplies,10,200
Notebook,Office Supplies,5,300
Stapler,Office Supplies,12,75
Because we are working with a .csv file, we will need Python's built-in csv library to read it.
The Script: generate_sales_report.py
generate_sales_report.pyThis will be our most comprehensive script yet. We'll build it step-by-step. Create a new file named generate_sales_report.py.
Step 1: Reading the CSV and Setting up the Workbook
First, we'll read the data from the CSV file and set up a new Excel workbook with a "Sales Data" sheet.
Step 2: Processing and Formatting the Data
Now, we'll loop through the data we just loaded, add a "Total Revenue" column with a formula, and apply the styling skills we learned in Chapter 4.
Step 3: Creating a Summary Sheet with a Chart
Finally, let's create a new sheet for a summary chart that visualizes the total revenue for each product.
Run the complete script. In a few seconds, you'll have a multi-sheet, fully-formatted report with data and a chart, all generated from a simple CSV file.
What You've Accomplished
You have successfully built a complete automation workflow. This case study demonstrates how the skills from previous chapters—reading data, looping, styling, formulas, and charting—come together to create a powerful and practical solution. You are now equipped with the knowledge to start automating your own Excel tasks.
Last updated