Files
the_information_nexus/tech_docs/python/openpyxl.md
2024-05-01 12:28:44 -06:00

3.2 KiB

For working with Excel documents using Python, the openpyxl library is a popular choice. It allows you to read and write Excel 2010 xlsx/xlsm/xltx/xltm files, providing capabilities to create new worksheets, change cell values, apply styles, and much more. Below is a concise reference guide for common use cases with openpyxl, formatted in Markdown syntax:

openpyxl Reference Guide

Installation

pip install openpyxl

Creating and Saving Workbooks

from openpyxl import Workbook

# Create a new workbook
wb = Workbook()

# Save the workbook
wb.save('path_to_file.xlsx')

Opening Existing Workbooks

from openpyxl import load_workbook

# Load an existing workbook
wb = load_workbook('path_to_existing_file.xlsx')

Working with Sheets

# Create a new sheet
ws1 = wb.create_sheet(title="Sheet1")

# Select a sheet
ws2 = wb["Sheet1"]

# List all sheet names
sheets = wb.sheetnames

# Remove a sheet
del wb["Sheet1"]

Writing to Cells

# Select a cell
cell = ws1['A1']

# Assign a value to the cell
ws1['A1'] = 'Hello'
ws1.cell(row=2, column=2, value="World")

# Iterate over rows and columns
for row in range(1, 5):
    for col in range(1, 3):
        ws1.cell(row=row, column=col, value=f'Row {row}, Col {col}')

Reading from Cells

# Read a cell's value
value = ws1['A1'].value

# Iterate over rows and columns
for row in ws1.iter_rows(min_row=1, max_col=2, max_row=2):
    for cell in row:
        print(cell.value)

Applying Styles

from openpyxl.styles import Font, Color, Alignment, Border, Side

# Create a font style
font = Font(name='Calibri', size=12, bold=True, italic=False, color="FF0000")

# Apply the font to a cell
ws1['A1'].font = font

# Create and apply border style
border = Border(left=Side(border_style="thin", color="000000"),
                right=Side(border_style="thin", color="000000"),
                top=Side(border_style="thin", color="000000"),
                bottom=Side(border_style="thin", color="000000"))
ws1['A1'].border = border

# Apply alignment
alignment = Alignment(horizontal="center", vertical="center")
ws1['A1'].alignment = alignment

Formulas

# Assign a formula to a cell
ws1['A3'] = '=SUM(A1:A2)'

Adding Charts

from openpyxl.chart import BarChart, Reference

# Create data for the chart
for i in range(10):
    ws1.append([i])

# Create a bar chart
chart = BarChart()
data = Reference(ws1, min_col=1, min_row=1, max_col=1, max_row=10)
chart.add_data(data, titles_from_data=True)

# Add the chart to the sheet
ws1.add_chart(chart, "E5")

Working with Rows and Columns

# Insert a row at the second position
ws1.insert_rows(2)

# Delete the third row
ws1.delete_rows(3)

# Insert a column
ws1.insert_cols(2)

# Delete a column
ws1.delete_cols(3)

# Set row height
ws1.row_dimensions[1].height = 20

# Set column width
ws1.column_dimensions['A'].width = 30

Save Changes

wb.save('path_to_file.xlsx')

This guide covers the basics of creating and manipulating Excel files with openpyxl, including operations on workbooks and worksheets, cell manipulation, applying styles, and adding charts. These capabilities allow for robust Excel document generation and editing directly from Python scripts.