Chapter 1: Introduction to Python and Your First Excel Script
Welcome to the first step on your journey to mastering Excel automation! In this chapter, we're going to dive right in. We'll get straight to the rewarding part: writing a Python script that creates a brand new Excel file and populates it with data. By the end of this chapter, you will have written and run your very first Excel automation script.
Your First Tool: The openpyxl Library
openpyxl LibraryTo work with Excel files in Python, we need a special tool, or what's known in Python as a "library." The most popular and powerful library for working with .xlsx files is openpyxl.
Before we can use it, we need to install it. Open your terminal or command prompt (like Command Prompt on Windows or Terminal on macOS/Linux) and type the following command:
pip install openpyxl
This command tells Python's package installer, pip, to download and install openpyxl so that our scripts can use it.
Writing Your First Script: Creating an Excel File
Now for the fun part. Let's write a script that creates a new Excel workbook, adds some data to a sheet, and saves the file.
Create a new file in your code editor and name it create_inventory.py. Type the following code into the file:
# 1. Import the Workbook class from the openpyxl library
from openpyxl import Workbook
# 2. Create a new, empty workbook object
wb = Workbook()
# 3. Select the active worksheet (it's created automatically)
ws = wb.active
# 4. Give the worksheet a new title
ws.title = "Inventory"
# 5. Add data to the worksheet
# Let's create a header row
ws['A1'] = "Product"
ws['B1'] = "Quantity"
ws['C1'] = "Price"
# Now let's add some data rows
ws['A2'] = "Laptop"
ws['B2'] = 15
ws['C2'] = 1200
ws['A3'] = "Mouse"
ws['B3'] = 50
ws['C3'] = 25
# 6. Save the workbook to a file
# This will create a new file named 'inventory.xlsx' in the same folder as your script
wb.save("inventory.xlsx")
print("Successfully created the inventory.xlsx file!")
Running Your Script
Save the create_inventory.py file. Now, go back to your terminal or command prompt, make sure you are in the same directory where you saved your file, and run the script with this command:
You should see the message: "Successfully created the inventory.xlsx file!"
Now, check the folder. You will find a new Excel file named inventory.xlsx. Open it, and you'll see the data you just created with your Python script!
What You've Accomplished
Congratulations! You have successfully written a Python script that automates the creation of an Excel file. You've learned how to install a necessary library, create a workbook, select a sheet, write data to cells, and save your work.
This is the fundamental building block for all Excel automation. In the next chapter, we'll learn how to open and read data from an existing Excel file.
Last updated