OpenPyXL for Beginners: Automate Excel with Python

openpyxl-beginners-automate-excel-python
Image by Editor
 

Excel is still a go-to tool for handling data at work. But once your sheet grows to thousands of rows, manually updating, analyzing, and generating reports can get very slow. OpenPyXL lets you hand this work over to Python. It is a Python library that reads, writes, and modifies Office Open XML format (.xlsx) files, letting you automate your workflows. In this article, I will show you the basics of the library, how to install it, create and manipulate workbooks, and set up some simple automation.

Installing OpenPyXL

Install it with pip:

 
pip install openpyxl

Then import it in your script:

 
import openpyxl

Key Concepts To Understand:

  • Workbook = the Excel file
  • Worksheet = a sheet inside the workbook
  • Cell = a single entry like A1
  • Rows / columns = groups of cells

A workbook can have many worksheets. Worksheets hold cells in rows and columns.

Creating a New File

 
import openpyxl

book = openpyxl.Workbook()
page = book.active
page.title = "Employees"

book.save("employees.xlsx")

Workbook() creates a new file. book.active gets the default sheet. book.save() writes the file to disk.

Writing Data to Excel

You can write data by referencing cells directly or by appending rows.

Direct cell assignment:

 
import openpyxl

doc = openpyxl.Workbook()
tab = doc.active

tab["A1"] = "Name"
tab["B1"] = "Age"

tab["A2"] = "Alice"
tab["B2"] = 25

tab["A3"] = "Bob"
tab["B3"] = 30

doc.save("employees.xlsx")

This creates a simple table in Excel. Excel cells follow a one-based indexing system (A1, B1, and so on), unlike Python lists, which are zero-based.

Instead of specifying cell coordinates manually, you can append rows.

Appending rows (useful for tables):

 
import openpyxl

report = openpyxl.Workbook()
sheet = report.active

sheet.append(["Name", "Salary"])
sheet.append(["Alice", 50000])
sheet.append(["Bob", 60000])

report.save("salary_report.xlsx")

This is useful when exporting data from databases or APIs.

Reading Data from an Excel File

Load a file and read cells:

 
import openpyxl

data_book = openpyxl.load_workbook("employees.xlsx")
data_tab = data_book.active

print(data_tab["A2"].value)

Output:

 
Alice

Loop through rows:

 
for row in data_tab.iter_rows(values_only=True):
    print(row)

values_only=True returns plain values instead of full cell objects.

Output:

 
('Name', 'Age')
('Alice', 25)
('Bob', 30)

Updating an Existing Excel File

Open the workbook, change values, and save again:

 
import openpyxl

file_book = openpyxl.load_workbook("employees.xlsx")
file_tab = file_book.active

file_tab["B2"] = 26
file_book.save("employees_updated.xlsx")

updated_book = openpyxl.load_workbook("employees_updated.xlsx")
updated_tab = updated_book.active

for row in updated_tab.iter_rows(values_only=True):
    print(row)

Output:

 
('Name', 'Age')
('Alice', 26)
('Bob', 30)

You can overwrite the same file if you want to.

Adding Excel Formulas

You can also write Excel formulas programmatically. For example, you can calculate totals:

 
from openpyxl import Workbook

wb = Workbook()
sheet = wb.active

sheet["A1"] = 100
sheet["A2"] = 200
sheet["A3"] = "=SUM(A1:A2)"

wb.save("totals.xlsx")

Note: OpenPyXL writes formulas but does not evaluate them. Excel calculates them when the file is opened.

Working with Multiple Sheets

Create and switch between sheets:

 
import openpyxl

wb = openpyxl.Workbook()
jan = wb.active
jan.title = "January"
feb = wb.create_sheet("February")

jan["A1"] = "Sales"
feb["A1"] = "Sales"

wb.save("sales_report.xlsx")

Access a sheet by name with wb[“January”].

Creating a Simple Automation Example

Filter rows and write the results to a new file:

 
import openpyxl

src = openpyxl.load_workbook("employees.xlsx")
src_tab = src.active

print("BEFORE FILTERING:")
for row in src_tab.iter_rows(values_only=True):
    print(row)

out_book = openpyxl.Workbook()
out_tab = out_book.active

out_tab.append(["Name", "Age"])

for name, age in src_tab.iter_rows(min_row=2, values_only=True):
    if age and age > 25:
        out_tab.append([name, age])

out_book.save("filtered_employees.xlsx")

filtered_book = openpyxl.load_workbook("filtered_employees.xlsx")
filtered_tab = filtered_book.active

print("\nAFTER FILTERING:")
for row in filtered_tab.iter_rows(values_only=True):
    print(row)

This reads the input, keeps rows where age > 25, and saves a new file.

Output:

 
BEFORE FILTERING:
('Name', 'Age')
('Alice', 25)
('Bob', 30)

AFTER FILTERING:
('Name', 'Age')
('Bob', 30)

Building an Employee Performance Report

In real-world workflows, you often get large spreadsheets and need more than just filtering. For example, you might want to:

  • Select employees by age, department, or role
  • Calculate bonuses automatically
  • Highlight top performers
  • Create a summary sheet with totals

Here is how you can do that with OpenPyXL. First, create some dummy data:

 
import random
import openpyxl

wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "Employees"

# Add headers
sheet.append(["Name", "Age", "Department", "Salary"])

# Dummy departments
departments = ["Sales", "Engineering", "HR", "Marketing"]

# Generate 10 dummy employees
for i in range(1, 11):
    name = f"Employee{i}"
    age = random.randint(22, 40)
    dept = random.choice(departments)
    salary = random.randint(40000, 90000)
    sheet.append([name, age, dept, salary])

wb.save("employees.xlsx")

for row in sheet.iter_rows(values_only=True):
    print(row)

Output:

 
('Name', 'Age', 'Department', 'Salary')
('Employee1', 30, 'Sales', 55442)
('Employee2', 28, 'Sales', 52123)
('Employee3', 22, 'Sales', 64796)
('Employee4', 34, 'Marketing', 47525)
('Employee5', 34, 'Sales', 44837)
('Employee6', 28, 'Engineering', 68631)
('Employee7', 35, 'Marketing', 51146)
('Employee8', 30, 'Marketing', 53049)
('Employee9', 36, 'Sales', 51337)
('Employee10', 32, 'HR', 84520)

Now, automate the report-building step:

 
import openpyxl
from openpyxl.styles import PatternFill, Font

src_wb = openpyxl.load_workbook("employees.xlsx")
src_sheet = src_wb.active

report_wb = openpyxl.Workbook()
r_sheet = report_wb.active
r_sheet.title = "Filtered Employees"

# Add headers
r_sheet.append(["Name", "Age", "Department", "Salary", "Bonus"])

# Style for high bonuses
highlight = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
bold = Font(bold=True)

# Summary stats
total_salary = 0
total_bonus = 0
high_bonus_count = 0

# Process rows
for name, age, dept, salary in src_sheet.iter_rows(min_row=2, values_only=True):
    if age > 25 and dept in ["Sales", "Engineering"]:
        bonus = round(salary * 0.10, 2)
        r_sheet.append([name, age, dept, salary, bonus])
        total_salary += salary
        total_bonus += bonus

        if bonus > 8000:
            row = r_sheet.max_row
            r_sheet[f"E{row}"].fill = highlight
            r_sheet[f"E{row}"].font = bold
            high_bonus_count += 1

for col in r_sheet.columns:
    max_length = max(len(str(c.value or "")) for c in col)
    r_sheet.column_dimensions[col[0].column_letter].width = max_length + 2

# Create summary sheet
summary = report_wb.create_sheet("Summary")
summary.append(["Metric", "Value"])
summary.append(["Employees Filtered", r_sheet.max_row - 1])
summary.append(["Total Salary", total_salary])
summary.append(["Total Bonus", total_bonus])
summary.append(["High Bonuses (>8000)", high_bonus_count])

report_wb.save("employee_report.xlsx")

for row in r_sheet.iter_rows(values_only=True):
    print(row)

Output:

 
('Name', 'Age', 'Department', 'Salary', 'Bonus')
('Employee1', 30, 'Sales', 55442, 5544.2)
('Employee2', 28, 'Sales', 52123, 5212.3)
('Employee5', 34, 'Sales', 44837, 4483.7)
('Employee6', 28, 'Engineering', 68631, 6863.1)
('Employee9', 36, 'Sales', 51337, 5133.7)

Tips

  • Do not load very large files into memory if you can avoid it
  • Use iter_rows() to process rows efficiently
  • Test scripts on copies before overwriting original files
  • Save intermediate files in long automation pipelines

Final Thoughts

OpenPyXL makes repetitive Excel work faster and more repeatable. A few simple scripts can replace hours of manual editing. Once you are comfortable with these basics, the next step is exploring more advanced features such as:

  • Cell formatting and styles
  • Charts and visualizations
  • Conditional formatting
  • Excel templates and automation pipelines

6 Replies to “OpenPyXL for Beginners: Automate Excel with Python”

  1. # Create summary sheet
    for col in r_sheet.columns:
    max_length = max(len(str(c.value or “”)) for c in col)
    for col in r_sheet.columns:
    # Create summary sheet
    min_length = min(len(str(c.value or “”)) for c in col)
    for 1 in range(0,1e97): # Create summary sheet
    snoobie = 1 + min(len(str(‘8’)))
    # Create summary sheet

  2. This guide has made me make very useful much to the python code python codeing I have learned very a much because the article page has the words and the code thanks.

  3. It should be noted that, first to install pip, one should initiate
    `python -m ensurepip` or `python3 -m ensurepip`, using `sudo`, then one can use `can use the –trusted-host option: python -m ensurepip –trusted-host pypi.org –trusted-host files.pythonhosted.org`
    pip –version

Leave a Reply

Your email address will not be published. Required fields are marked *