Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions openpyxl-excel-spreadsheets-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# A Guide to Excel Spreadsheets in Python With openpyxl

This folder contains the sample code and dataset for the Real Python tutorial [A Guide to Excel Spreadsheets in Python With openpyxl](https://realpython.com/openpyxl-excel-spreadsheets-python/).

- `reviews-sample.xlsx`: the sample dataset of Amazon product reviews that the tutorial calls `sample.xlsx`
- `hello_world.py` and `append_data.py`: creating a spreadsheet and appending data to it
- `reading.py`, `iterating.py`, and `products_dict.py`: reading and iterating through the dataset
- `classes.py`, `mapping.py`, and `parse_reviews.py`: converting rows into data classes
- `cells_rows_columns.py` and `managing_sheets.py`: basic spreadsheet operations
- `freeze_and_filter.py`, `formulas.py`, `styles.py`, and `conditional_formatting.py`: freezing panes, filters, formulas, styles, and conditional formatting
- `add_image.py`: adding an image to a spreadsheet
- `bar_chart.py` and `line_chart.py`: adding charts
- `db_classes.py` and `export_classes.py`: exporting data classes to a spreadsheet with a chart
- `pandas_to_excel.py` and `excel_to_pandas.py`: converting between pandas DataFrames and workbooks

## Setup

Create and activate a virtual environment, then install the pinned dependencies:

```sh
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

The code requires Python 3.11 or later.

## Usage

Run the scripts from this folder. Start with `hello_world.py`, because `append_data.py`, `cells_rows_columns.py`, and `add_image.py` open the `hello_world.xlsx` file it creates:

```sh
(venv) $ python hello_world.py
(venv) $ python append_data.py
(venv) $ python parse_reviews.py
```

Before you run `add_image.py`, save an image as `logo.png` in this folder, as the tutorial describes.

Each script saves its result as a new `.xlsx` file, so you can open it in your spreadsheet editor.
15 changes: 15 additions & 0 deletions openpyxl-excel-spreadsheets-python/add_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from openpyxl import load_workbook
from openpyxl.drawing.image import Image

# Let's use the hello_world spreadsheet since it has less data
workbook = load_workbook(filename="hello_world.xlsx")
sheet = workbook.active

logo = Image("logo.png")

# A bit of resizing to not fill the whole spreadsheet with the logo
logo.height = 150
logo.width = 150

sheet.add_image(logo, "A3")
workbook.save(filename="hello_world_logo.xlsx")
11 changes: 11 additions & 0 deletions openpyxl-excel-spreadsheets-python/append_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from openpyxl import load_workbook

# Start by opening the spreadsheet and selecting the main sheet
workbook = load_workbook(filename="hello_world.xlsx")
sheet = workbook.active

# Write what you want into a specific cell
sheet["C1"] = "writing ;)"

# Save the spreadsheet
workbook.save(filename="hello_world_append.xlsx")
28 changes: 28 additions & 0 deletions openpyxl-excel-spreadsheets-python/bar_chart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

workbook = Workbook()
sheet = workbook.active

# Let's create some sample sales data
rows = [
["Product", "Online", "Store"],
[1, 30, 45],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 25],
[6, 25, 35],
[7, 20, 40],
]

for row in rows:
sheet.append(row)

chart = BarChart()
data = Reference(worksheet=sheet, min_row=1, max_row=8, min_col=2, max_col=3)

chart.add_data(data, titles_from_data=True)
sheet.add_chart(chart, "E2")

workbook.save("chart.xlsx")
49 changes: 49 additions & 0 deletions openpyxl-excel-spreadsheets-python/cells_rows_columns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from openpyxl import load_workbook

workbook = load_workbook(filename="hello_world.xlsx")
sheet = workbook.active


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


# Update a cell value
cell = sheet["A1"]
print(cell)
print(repr(cell.value))
cell.value = "hey"
print(repr(cell.value))
cell.value = "hello"

# Adding a value to row 10 creates the rows in between
print_rows()
sheet["B10"] = "test"
print_rows()
sheet.delete_rows(idx=2, amount=9)

# Insert a column before the existing column 1 ("A")
sheet.insert_cols(idx=1)
print_rows()

# Insert 5 columns between column 2 ("B") and 3 ("C")
sheet.insert_cols(idx=3, amount=5)
print_rows()

# Delete the created columns
sheet.delete_cols(idx=3, amount=5)
sheet.delete_cols(idx=1)
print_rows()

# Insert a new row in the beginning
sheet.insert_rows(idx=1)
print_rows()

# Insert 3 new rows in the beginning
sheet.insert_rows(idx=1, amount=3)
print_rows()

# Delete the first 4 rows
sheet.delete_rows(idx=1, amount=4)
print_rows()
20 changes: 20 additions & 0 deletions openpyxl-excel-spreadsheets-python/classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import datetime
from dataclasses import dataclass


@dataclass
class Product:
id: str
parent: str
title: str
category: str


@dataclass
class Review:
id: str
customer_id: str
stars: int
headline: str
body: str
date: datetime.datetime
70 changes: 70 additions & 0 deletions openpyxl-excel-spreadsheets-python/conditional_formatting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from openpyxl import load_workbook
from openpyxl.formatting.rule import (
ColorScaleRule,
DataBarRule,
IconSetRule,
Rule,
)
from openpyxl.styles import PatternFill
from openpyxl.styles.differential import DifferentialStyle

FILENAME = "reviews-sample.xlsx"

# Red background for all reviews with less than 3 stars
workbook = load_workbook(filename=FILENAME)
sheet = workbook.active
red_background = PatternFill(fgColor="00FF0000")
diff_style = DifferentialStyle(fill=red_background)
rule = Rule(type="expression", dxf=diff_style)
rule.formula = ["$H1<3"]
sheet.conditional_formatting.add("A1:O100", rule)
workbook.save("sample_conditional_formatting.xlsx")

# Color gradient from red to green on the star ratings, column "H"
workbook = load_workbook(filename=FILENAME)
sheet = workbook.active
color_scale_rule = ColorScaleRule(
start_type="min",
start_color="00FF0000", # Red
end_type="max",
end_color="0000FF00", # Green
)
sheet.conditional_formatting.add("H2:H100", color_scale_rule)
workbook.save(filename="sample_conditional_formatting_color_scale.xlsx")

# Two gradients: red to yellow, then yellow to green
workbook = load_workbook(filename=FILENAME)
sheet = workbook.active
color_scale_rule = ColorScaleRule(
start_type="num",
start_value=1,
start_color="00FF0000", # Red
mid_type="num",
mid_value=3,
mid_color="00FFFF00", # Yellow
end_type="num",
end_value=5,
end_color="0000FF00", # Green
)
sheet.conditional_formatting.add("H2:H100", color_scale_rule)
workbook.save(filename="sample_conditional_formatting_color_scale_3.xlsx")

# Icon set
workbook = load_workbook(filename=FILENAME)
sheet = workbook.active
icon_set_rule = IconSetRule("5Arrows", "num", [1, 2, 3, 4, 5])
sheet.conditional_formatting.add("H2:H100", icon_set_rule)
workbook.save("sample_conditional_formatting_icon_set.xlsx")

# Data bar
workbook = load_workbook(filename=FILENAME)
sheet = workbook.active
data_bar_rule = DataBarRule(
start_type="num",
start_value=1,
end_type="num",
end_value="5",
color="0000FF00", # Green
)
sheet.conditional_formatting.add("H2:H100", data_bar_rule)
workbook.save("sample_conditional_formatting_data_bar.xlsx")
13 changes: 13 additions & 0 deletions openpyxl-excel-spreadsheets-python/db_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from dataclasses import dataclass


@dataclass
class Sale:
quantity: int


@dataclass
class Product:
id: str
name: str
sales: list[Sale]
32 changes: 32 additions & 0 deletions openpyxl-excel-spreadsheets-python/excel_to_pandas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import pandas as pd
from openpyxl import load_workbook

from mapping import REVIEW_ID

workbook = load_workbook(filename="reviews-sample.xlsx")
sheet = workbook.active

# Convert the sheet into a DataFrame as is
values = sheet.values
df = pd.DataFrame(values)
print(df.shape)

# Add the correct headers and use the review ID as the index
data = sheet.values

# Set the first row as the columns for the DataFrame
cols = next(data)
data = list(data)

# Set the field "review_id" as the indexes for each row
idx = [row[REVIEW_ID] for row in data]

df = pd.DataFrame(data, index=idx, columns=cols)

print(df.columns)

# Get first 10 reviews' star rating
print(df["star_rating"][:10])

# Grab review with id "R2EQL1V1L6E0C9", using the index
print(df.loc["R2EQL1V1L6E0C9"])
57 changes: 57 additions & 0 deletions openpyxl-excel-spreadsheets-python/export_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import random

from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference

from db_classes import Product, Sale

products = []

# Let's create 5 products
for idx in range(1, 6):
sales = []

# Create 5 months of sales
for _ in range(5):
sale = Sale(quantity=random.randrange(5, 100))
sales.append(sale)

product = Product(id=str(idx), name="Product %s" % idx, sales=sales)
products.append(product)

workbook = Workbook()
sheet = workbook.active

# Append column names first
sheet.append(
[
"Product ID",
"Product Name",
"Month 1",
"Month 2",
"Month 3",
"Month 4",
"Month 5",
]
)

# Append the data
for product in products:
data = [product.id, product.name]
for sale in product.sales:
data.append(sale.quantity)
sheet.append(data)

chart = LineChart()
data = Reference(worksheet=sheet, min_row=2, max_row=6, min_col=2, max_col=7)

chart.add_data(data, titles_from_data=True, from_rows=True)
sheet.add_chart(chart, "B8")

cats = Reference(worksheet=sheet, min_row=1, max_row=1, min_col=3, max_col=7)
chart.set_categories(cats)

chart.x_axis.title = "Months"
chart.y_axis.title = "Sales (per unit)"

workbook.save(filename="oop_sample.xlsx")
15 changes: 15 additions & 0 deletions openpyxl-excel-spreadsheets-python/formulas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from openpyxl import load_workbook
from openpyxl.utils import FORMULAE

print(len(FORMULAE), "formulas supported, for example:", sorted(FORMULAE)[:5])

workbook = load_workbook(filename="reviews-sample.xlsx")
sheet = workbook.active

# Star rating is column "H"
sheet["P2"] = "=AVERAGE(H2:H100)"

# The helpful votes are counted on column "I"
sheet["P3"] = '=COUNTIF(I2:I100, ">0")'

workbook.save(filename="sample_formulas.xlsx")
15 changes: 15 additions & 0 deletions openpyxl-excel-spreadsheets-python/freeze_and_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from openpyxl import load_workbook

workbook = load_workbook(filename="reviews-sample.xlsx")
sheet = workbook.active
sheet.freeze_panes = "C2"
workbook.save("sample_frozen.xlsx")

workbook = load_workbook(filename="reviews-sample.xlsx")
sheet = workbook.active

# Check the used spreadsheet space using the attribute "dimensions"
print(sheet.dimensions)

sheet.auto_filter.ref = "A1:O100"
workbook.save(filename="sample_with_filters.xlsx")
11 changes: 11 additions & 0 deletions openpyxl-excel-spreadsheets-python/hello_world.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from openpyxl import Workbook

filename = "hello_world.xlsx"

workbook = Workbook()
sheet = workbook.active

sheet["A1"] = "hello"
sheet["B1"] = "world!"

workbook.save(filename=filename)
Loading
Loading