2 min read

Python Openpyxl Module

openpyxl is a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files. It allows you to manipulate Excel files without needing Excel installed.

Installation

pip install openpyxl

Creating a Workbook

To create a new Excel file, you start by creating a Workbook object.

from openpyxl import Workbook

wb = Workbook()

# Grab the active worksheet
ws = wb.active

# Change the title of the worksheet
ws.title = "New Title"

Writing Data

Accessing Cells Directly

You can access cells using their coordinate keys (e.g., 'A1').

ws['A1'] = 42

Using Row and Column Notation

# Row 2, Column 3 (C2)
ws.cell(row=2, column=3, value=10)

Appending Rows

You can append a list of values as a new row at the bottom of the worksheet.

ws.append(["Name", "Age", "City"])
ws.append(["Alice", 30, "New York"])
ws.append(["Bob", 25, "Los Angeles"])

Saving a Workbook

wb.save("sample.xlsx")

Loading a Workbook

To read an existing Excel file, use load_workbook.

from openpyxl import load_workbook

wb = load_workbook("sample.xlsx")

# Get a specific sheet by name
ws = wb["New Title"]

Reading Data

Reading a Single Cell

print(ws['A1'].value)

Iterating Through Rows

You can iterate through rows using iter_rows().

for row in ws.iter_rows(min_row=1, max_col=3, values_only=True):
    print(row)

programming/python/python