Initializing a new spreadsheet requires instantiating a Workbook object from the openpyxl library. Upon creation, a default worksheet named "Sheet" is automatically generated. The active worksheet can be referenced directly, and its display name is controlled via the .title attribute. Modifications to workbook structure or cell values reside in memory until explicitly persisted using the .save() method.
Sheet Management and Structure
Worksheets can be dynamicallly inserted or removed. The create_sheet() method accepts optional index and title parameters to control placement and labeling. Removing a worksheet is achieved by passing the target reference to the deletion handler.
from openpyxl import Workbook
workbook = Workbook()
active_sheet = workbook.active
print(f"Initial name: {active_sheet.title}")
active_sheet.title = "Q1_Report"
# Insert worksheets at specific positions
workbook.create_sheet(index=0, title="Summary")
workbook.create_sheet(index=1, title="Raw_Data")
# Verify sheet structure
print(workbook.sheetnames)
# Remove a worksheet by its reference
target_sheet = workbook["Raw_Data"]
workbook.remove(target_sheet)
print(workbook.sheetnames)
workbook.save("financial_template.xlsx")
Direct Cell Population
Assigning data to individual cells follows a dictionary-like syntax using standard Excel coordinate notation, or can be handled via row/column indices for programmatic generation.
import openpyxl
file_obj = openpyxl.Workbook()
target_sheet = file_obj.active
target_sheet["C4"] = "Initialization Complete"
# Verify assignment
print(target_sheet["C4"].value)
Bulk Data Insersion Strategies
For structured datasets, the .append() method efficiently adds rows to a worksheet. It accepts ietrables such as lists, tuples, or range objects. Alternatively, nested iteration over row and column indices allows precise coordinate mapping.
import openpyxl
from openpyxl.utils import get_column_letter
book = openpyxl.Workbook()
# Method 1: Appending sequences
matrix_sheet = book.create_sheet("Numeric_Grid")
for row_idx in range(1, 41):
matrix_sheet.append(range(20))
# Method 2: Appending structured records
record_sheet = book.create_sheet("Sales_Data")
dataset = [
["Product_ID", "Batch_A", "Batch_B"],
[101, 450, 320],
[102, 400, 290],
[103, 550, 410],
[104, 300, 280],
]
for entry in dataset:
record_sheet.append(entry)
# Method 3: Coordinate-based writing
grid_sheet = book.create_sheet(title="Matrix_Fill")
for current_row in range(6, 31):
for current_col in range(16, 55):
coord_letter = get_column_letter(current_col)
grid_sheet.cell(row=current_row, column=current_col, value=coord_letter)
print(grid_sheet["AA10"].value)
book.save("generated_report.xlsx")
Modifying Existing Spreadsheet Content
Updating specific records in an existing file involves loading the document, iterating through relevant rows, evaluating conditions, and overwriting targeted cells. The modified workbook must be saved under a new filename or overwrite the original to preserve changes.
import openpyxl
price_adjustments = {
"Garlic": 3.25,
"Celery": 1.30,
"Lemon": 1.15
}
doc = openpyxl.load_workbook("inventory_data.xlsx")
sheet = doc.active
# Iterate starting from the second row to bypass headers
for row_index in range(2, sheet.max_row + 1):
item_name = sheet.cell(row=row_index, column=1).value
if item_name in price_adjustments:
# Update the price in column 2
sheet.cell(row=row_index, column=2).value = price_adjustments[item_name]
doc.save("inventory_updated.xlsx")