ZetCode

Python openpyxl

last modified November 17, 2026 Python 3.15

In this article we show how to work with Excel files in Python using the openpyxl library.

Openpyxl

The openpyxl is a Python library to read and write Excel 2010 xlsx/xlsm/xltx/xltm files. It works with the files directly; neither Excel nor any other spreadsheet application is needed. The examples in this article use openpyxl 3.1.

Excel xlsx

In this article we work with xlsx files. The xlsx is a file extension for an open XML spreadsheet file format used by Microsoft Excel. It is a zip archive of XML files based on the Office Open XML standard. The xlsm files support macros. The older xls format is a proprietary binary format, which openpyxl does not support.

We install openpyxl with the pip tool. The Pillow library is needed only for the example that inserts an image.

$ pip install openpyxl pillow

Creating a new file

In the first example, we create a new xlsx file with openpyxl.

write_xlsx.py
from datetime import date

from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet['A1'] = 56
sheet['A2'] = 43
sheet['A3'] = date.today()

book.save('sample.xlsx')

In the example, we create a new xlsx file. We write data into three cells.

from openpyxl import Workbook

We import the Workbook class from the openpyxl module. A workbook is the container for all other parts of the document.

book = Workbook()

A new workbook is created. A workbook is always created with at least one worksheet.

sheet = book.active

We get the reference to the active sheet with the active property.

sheet['A1'] = 56
sheet['A2'] = 43

We write numerical data to cells A1 and A2.

sheet['A3'] = date.today()

We write the current date to the cell A3. Python dates and datetimes are stored as Excel dates with a date number format.

book.save('sample.xlsx')

We write the contents to the sample.xlsx file with the save method. An existing file is overwritten.

Writing to a cell

There are two basic ways to write to a cell: using a key of a worksheet such as A1 or D3, or using a row and column notation with the cell method. Rows and columns are numbered from 1.

write2cell.py
from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet['A1'] = 1
sheet.cell(row=2, column=2).value = 2
sheet.cell(row=3, column=3, value=3)

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

book.save('write2cell.xlsx')

In the example, we write three values to three cells.

sheet['A1'] = 1

Here, we assign a numerical value to the A1 cell.

sheet.cell(row=2, column=2).value = 2
sheet.cell(row=3, column=3, value=3)

We write to cells B2 and C3 with the row and column notation. The cell method can set the value directly with the value parameter.

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

We print the values of the sheet row by row; empty cells are None.

$ python write2cell.py
(1, None, None)
(None, 2, None)
(None, None, 3)

Appending values

With the append method, we can append a group of values at the bottom of the current sheet. The following program creates the items.xlsx file, which we use in the next examples.

create_items.py
from openpyxl import Workbook
from openpyxl.styles import Font

book = Workbook()
sheet = book.active

rows = (
    ('Items', 'Quantity'),
    ('coins', 23),
    ('chairs', 3),
    ('pencils', 5),
    ('bottles', 8),
    ('books', 30),
)

for row in rows:
    sheet.append(row)

for cell in sheet[1]:
    cell.font = Font(bold=True)

sheet.column_dimensions['A'].width = 12

print(f'{sheet.max_row} rows, {sheet.max_column} columns')

book.save('items.xlsx')

We append a header and five rows of data to the sheet. The header is formatted in bold.

for row in rows:
    sheet.append(row)

We go through the container row by row and insert the data with the append method. Each value goes to the next column.

for cell in sheet[1]:
    cell.font = Font(bold=True)

The sheet[1] expression returns the cells of the first row. We set a bold font for each of them. Styles in openpyxl are immutable; we assign a new Font object instead of modifying the existing one.

sheet.column_dimensions['A'].width = 12

We make the first column wider.

Items
Figure: Items
$ python create_items.py
6 rows, 2 columns

Reading cells

In the following example, we read the data written by the first example from the sample.xlsx file.

read_cells.py
import openpyxl

book = openpyxl.load_workbook('sample.xlsx')
sheet = book.active

a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)

print(a1.value)
print(a2.value)
print(a3.value)

print(a3.is_date, a3.number_format)
print(a1.coordinate, a1.data_type, a3.data_type)

The example loads an existing xlsx file and reads three cells.

book = openpyxl.load_workbook('sample.xlsx')

The file is opened with the load_workbook function.

a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)

We get the A1, A2, and A3 cells. In the third line, we use the cell method to get the A3 cell.

print(a3.is_date, a3.number_format)
print(a1.coordinate, a1.data_type, a3.data_type)

The date is read back as a datetime object. The is_date and number_format attributes tell how the value is stored. The data type is n for numbers and d for dates.

$ python read_cells.py
56
43
2026-11-17 00:00:00
True yyyy-mm-dd
A1 n d

Reading multiple cells

We read the data of the items.xlsx file using a range operator.

read_range.py
import openpyxl

book = openpyxl.load_workbook('items.xlsx')
sheet = book.active

cells = sheet['A1':'B6']

for c1, c2 in cells:
    print(f'{c1.value:8} {c2.value:>8}')

In the example, we read data from two columns using a range operation.

cells = sheet['A1':'B6']

In this line, we read data from cells A1 to B6. The result is a tuple of rows, each of them a tuple of cells.

for c1, c2 in cells:
    print(f'{c1.value:8} {c2.value:>8}')

We unpack the two cells of each row and format their values for neat output on the console.

$ python read_range.py
Items    Quantity
coins          23
chairs          3
pencils         5
bottles         8
books          30

Iterating by rows

The iter_rows method returns cells from the worksheet as rows. The min_row, max_row, min_col, and max_col parameters limit the area; the defaults cover all cells with data.

iterating_by_rows.py
import openpyxl

book = openpyxl.load_workbook('items.xlsx')
sheet = book.active

for row in sheet.iter_rows(min_row=2, max_row=4, max_col=2):
    print('  '.join(f'{cell.coordinate}={cell.value}' for cell in row))

print('--')

for name, quantity in sheet.iter_rows(min_row=2, values_only=True):
    print(name, quantity)

First, we iterate over three rows and print the coordinates and values of the cells. With values_only=True, the method returns the cell values instead of the cell objects, so each row can be unpacked directly into variables.

$ python iterating_by_rows.py
A2=coins  B2=23
A3=chairs  B3=3
A4=pencils  B4=5
--
coins 23
chairs 3
pencils 5
bottles 8
books 30

Iterating by columns

The iter_cols method returns cells from the worksheet as columns.

iterating_by_columns.py
import openpyxl

book = openpyxl.load_workbook('items.xlsx')
sheet = book.active

for col in sheet.iter_cols(min_row=2, values_only=True):
    print(col)

print('--')

quantities = [cell.value for cell in sheet['B'][1:]]
print(quantities, sum(quantities))

We print the values of both columns, skipping the header. A single column can also be accessed by its letter; sheet['B'] returns a tuple of the cells of the column B.

$ python iterating_by_columns.py
('coins', 'chairs', 'pencils', 'bottles', 'books')
(23, 3, 5, 8, 30)
--
[23, 3, 5, 8, 30] 69

Statistics

For the next example, we need an xlsx file containing numbers. The following program creates 25 rows of random numbers in 10 columns. The generator is seeded, so the numbers are the same on each run.

create_numbers.py
import random

from openpyxl import Workbook

random.seed(7)

book = Workbook()
sheet = book.active

for _ in range(25):
    sheet.append([random.randint(0, 100) for _ in range(10)])

book.save('numbers.xlsx')

The randint function returns random integers from 0 to 100, inclusive.

mystats.py
import statistics as stats

import openpyxl

book = openpyxl.load_workbook('numbers.xlsx', read_only=True)
sheet = book.active

values = [val for row in sheet.iter_rows(values_only=True) for val in row]

book.close()

print(f'Number of values: {len(values)}')
print(f'Sum of values: {sum(values)}')
print(f'Minimum value: {min(values)}')
print(f'Maximum value: {max(values)}')
print(f'Mean: {stats.mean(values)}')
print(f'Median: {stats.median(values)}')
print(f'Standard deviation: {stats.stdev(values)}')
print(f'Variance: {stats.variance(values)}')

In the example, we read all values from the sheet and compute some basic statistics.

book = openpyxl.load_workbook('numbers.xlsx', read_only=True)

The read-only mode loads the cells lazily, which is much faster and uses less memory with large files. A read-only workbook should be closed with close when we are done with it.

values = [val for row in sheet.iter_rows(values_only=True) for val in row]

The nested comprehension flattens the rows into a single list of values.

print(f'Mean: {stats.mean(values)}')
print(f'Median: {stats.median(values)}')

Some of the functions are built-in, others come from the statistics module.

$ python mystats.py
Number of values: 250
Sum of values: 11868
Minimum value: 0
Maximum value: 99
Mean: 47.472
Median: 49.5
Standard deviation: 28.19882819633799
Variance: 795.1739116465864

Filter and sort data

A sheet has an auto_filter attribute, which allows to set filtering and sorting conditions. Note that openpyxl only writes the conditions to the file; the spreadsheet application applies them.

filter_sort.py
from openpyxl import Workbook

book = Workbook()
sheet = book.active

data = [
    ['Item', 'Colour'],
    ['pen', 'brown'],
    ['book', 'black'],
    ['plate', 'white'],
    ['chair', 'brown'],
    ['coin', 'gold'],
    ['bed', 'brown'],
    ['notebook', 'white'],
]

for r in data:
    sheet.append(r)

sheet.auto_filter.ref = 'A1:B8'
sheet.auto_filter.add_filter_column(1, ['brown', 'white'])
sheet.auto_filter.add_sort_condition('B2:B8')

print(sheet.auto_filter.ref)
print(sheet.auto_filter.filterColumn[0].filters.filter)

book.save('filtered.xlsx')

In the example, we create a sheet with items and their colours. We set an auto filter on the A1:B8 range, a filter on the second column (columns are indexed from 0 here) that shows brown and white items, and a sort condition on the colours. Then we print the filter range and the values of the column filter.

$ python filter_sort.py
A1:B8
['brown', 'white']

Dimensions

To get those cells that actually contain data, we can use dimensions.

dimensions.py
from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet['A3'] = 39
sheet['B3'] = 19

rows = [
    (88, 46),
    (89, 38),
    (23, 59),
    (56, 21),
    (24, 18),
    (34, 15)
]

for row in rows:
    sheet.append(row)

print(sheet.dimensions)
print(f'Minimum row: {sheet.min_row}')
print(f'Maximum row: {sheet.max_row}')
print(f'Minimum column: {sheet.min_column}')
print(f'Maximum column: {sheet.max_column}')

for c1, c2 in sheet[sheet.dimensions]:
    print(c1.value, c2.value)

book.save('dimensions.xlsx')

The example calculates the dimensions of two columns of data. We start adding data at the third row; the append method continues after the last row with data.

print(sheet.dimensions)

The dimensions property returns the top-left and bottom-right cell of the area of non-empty cells.

print(f'Minimum row: {sheet.min_row}')
print(f'Maximum row: {sheet.max_row}')

With the min_row and max_row properties, we get the minimum and maximum row containing data. Similarly, min_column and max_column give the columns.

for c1, c2 in sheet[sheet.dimensions]:
    print(c1.value, c2.value)

We use the dimensions string as a range to iterate through the data.

$ python dimensions.py
A3:B9
Minimum row: 3
Maximum row: 9
Minimum column: 1
Maximum column: 2
39 19
88 46
89 38
23 59
56 21
24 18
34 15

Creating sheets

Each workbook can have multiple sheets. The following program creates a workbook with three sheets.

create_sheets.py
from openpyxl import Workbook

book = Workbook()

jan = book.active
jan.title = 'January'

book.create_sheet('February')
book.create_sheet('March')

for i, sheet in enumerate(book.worksheets, start=1):
    sheet.append(['Month', 'Sales'])
    sheet.append([sheet.title, i * 1000])

book.save('sheets.xlsx')

We rename the default sheet and add two more sheets with create_sheet. The worksheets property returns the list of all sheets; we add a small table to each of them.

Sheets
Figure: Sheets

Working with sheets

The next program reads the workbook and accesses its sheets.

sheets.py
import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

print(book.sheetnames)

active_sheet = book.active
print(type(active_sheet))
print(active_sheet.title)

sheet = book['March']
print(sheet.title, sheet['B2'].value)

for sheet in book:
    print(sheet.title, sheet.max_row)

The program works with Excel sheets.

print(book.sheetnames)

The sheetnames property returns the names of the sheets in a workbook.

active_sheet = book.active
print(type(active_sheet))

We get the active sheet and print its type to the terminal.

sheet = book['March']

We get a reference to a sheet by its name. The older get_sheet_by_name and get_sheet_names methods are deprecated.

for sheet in book:
    print(sheet.title, sheet.max_row)

Iterating over a workbook yields its sheets.

$ python sheets.py
['January', 'February', 'March']
<class 'openpyxl.worksheet.worksheet.Worksheet'>
January
March 3000
January 2
February 2
March 2

Adding and removing sheets

Sheets can be created, removed, moved, and copied.

sheets2.py
import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

book.create_sheet('April')
print(book.sheetnames)

book.remove(book['January'])
print(book.sheetnames)

book.create_sheet('January', 0)
print(book.sheetnames)

book.move_sheet('April', offset=-1)
print(book.sheetnames)

copy = book.copy_worksheet(book['March'])
print(copy.title, copy['B2'].value)

book.save('sheets2.xlsx')

In this example, we modify the sheets of the workbook.

book.create_sheet('April')

A new sheet is created with the create_sheet method. It is appended after the last sheet.

book.remove(book['January'])

A sheet is removed with the remove method; the deprecated remove_sheet method did the same.

book.create_sheet('January', 0)

A new sheet can be created at the specified position; in our case, we create a new sheet at the position with index 0.

book.move_sheet('April', offset=-1)

The move_sheet method moves a sheet by the given offset.

copy = book.copy_worksheet(book['March'])

The copy_worksheet method copies a sheet within the workbook, including its data and styles.

$ python sheets2.py
['January', 'February', 'March', 'April']
['February', 'March', 'April']
['January', 'February', 'March', 'April']
['January', 'February', 'April', 'March']
March Copy 3000

Tab colour

It is possible to change the colour of a worksheet tab.

sheets3.py
import openpyxl

book = openpyxl.load_workbook('sheets.xlsx')

sheet = book['March']
sheet.sheet_properties.tabColor = '0072BA'

print(sheet.sheet_properties.tabColor.rgb)

book.save('sheets3.xlsx')

The example modifies the tab colour of the sheet titled "March". We change the tabColor property to a new colour given as an RGB hex string. openpyxl stores colours in ARGB format, so the colour is read back with the alpha component.

Tab colour of a worksheet
Figure: Tab colour of a worksheet
$ python sheets3.py
000072BA

Merging cells

Cells can be merged with the merge_cells method and unmerged with the unmerge_cells method. When we merge cells, only the top-left one keeps its value; the others become read-only MergedCell objects.

merging_cells.py
from openpyxl import Workbook
from openpyxl.styles import Alignment

book = Workbook()
sheet = book.active

sheet.merge_cells('A1:B2')

cell = sheet.cell(row=1, column=1)
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')

print(sheet.merged_cells.ranges)
print(type(sheet['B2']).__name__)

book.save('merging.xlsx')

In the example, we merge four cells: A1, B1, A2, and B2. The text in the final cell is centered.

from openpyxl.styles import Alignment

In order to center a text in the final cell, we use the Alignment class from the openpyxl.styles module.

sheet.merge_cells('A1:B2')

We merge four cells with the merge_cells method.

cell = sheet.cell(row=1, column=1)
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')

We set text to the merged cell and update its alignment.

Merged cells
Figure: Merged cells
$ python merging_cells.py
{<MergedCellRange A1:B2>}
MergedCell

Freezing panes

When we freeze panes, we keep an area of a worksheet visible while scrolling to another area of the worksheet.

freezing.py
from openpyxl import Workbook

book = Workbook()
sheet = book.active

sheet.append(['Name', 'Jan', 'Feb', 'Mar'])

for i in range(1, 51):
    sheet.append([f'item {i}', i, i * 2, i * 3])

sheet.freeze_panes = 'B2'
print(sheet.freeze_panes)

book.save('freezing.xlsx')

We create a table with a header and fifty rows and freeze the panes at the cell B2. The rows above and the columns to the left of the cell stay visible: the header row and the column with the names.

$ python freezing.py
B2

Formulas

The next example shows how to use formulas. openpyxl does not do calculations; it writes formulas into cells.

formulas.py
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Font

book = Workbook()
sheet = book.active

rows = (
    (34, 26),
    (88, 36),
    (24, 29),
    (15, 22),
    (56, 13),
    (76, 18)
)

for row in rows:
    sheet.append(row)

cell = sheet.cell(row=7, column=2)
cell.value = '=SUM(A1:B6)'
cell.font = Font(bold=True)

book.save('formulas.xlsx')

book = openpyxl.load_workbook('formulas.xlsx')
print(book.active['B7'].value)

book = openpyxl.load_workbook('formulas.xlsx', data_only=True)
print(book.active['B7'].value)

In the example, we calculate the sum of all values with the SUM function and style the output in bold font.

cell = sheet.cell(row=7, column=2)
cell.value = '=SUM(A1:B6)'
cell.font = Font(bold=True)

A formula is a string starting with the equals sign. We write it into the B7 cell and set a bold font.

book = openpyxl.load_workbook('formulas.xlsx', data_only=True)
print(book.active['B7'].value)

By default, a loaded cell contains the formula. With the data_only option, we get the value last calculated by a spreadsheet application. Our file was never opened in such an application, so there is no cached value and we get None. The figure shows the file opened in LibreOffice Calc, which computes the sum.

Calculating the sum of values
Figure: Calculating the sum of values
$ python formulas.py
=SUM(A1:B6)
None

Images

In the following example, we show how to insert an image into a sheet. The Image class requires the Pillow library.

write_image.py
from openpyxl import Workbook
from openpyxl.drawing.image import Image

book = Workbook()
sheet = book.active

img = Image('pythonlogo.png')
print(img.width, img.height, img.format)

sheet['A1'] = 'This is the Python logo'
sheet.add_image(img, 'B2')

book.save('sheet_image.xlsx')

In the example, we write an image into a sheet.

from openpyxl.drawing.image import Image

We work with the Image class from the openpyxl.drawing.image module.

img = Image('pythonlogo.png')
print(img.width, img.height, img.format)

A new Image object is created. The pythonlogo.png image is located in the current working directory. We print its size in pixels and its format.

sheet.add_image(img, 'B2')

We add the image with the add_image method; its top-left corner is anchored at the cell B2.

$ python write_image.py
149 148 png

Charts

The openpyxl library supports creation of various charts, including bar charts, line charts, area charts, bubble charts, scatter charts, and pie charts. According to the documentation, openpyxl supports chart creation within a worksheet only. Charts in existing workbooks will be lost when the workbook is loaded and saved.

create_bar_chart.py
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference

book = Workbook()
sheet = book.active

rows = [
    ('USA', 46),
    ('China', 38),
    ('UK', 29),
    ('Russia', 22),
    ('South Korea', 13),
    ('Germany', 11)
]

for row in rows:
    sheet.append(row)

data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)
categs = Reference(sheet, min_col=1, min_row=1, max_row=6)

chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)

chart.legend = None
chart.y_axis.majorGridlines = None
chart.varyColors = True
chart.title = 'Olympic Gold medals in London'

sheet.add_chart(chart, 'A8')

print(len(sheet._charts))

book.save('bar_chart.xlsx')

In the example, we create a bar chart to show the number of Olympic gold medals per country in London 2012.

from openpyxl.chart import BarChart, Reference

The openpyxl.chart module has tools to work with charts.

data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)

With the Reference class, we refer to the cells in the sheet that represent data. In our case, these are the numbers of Olympic gold medals.

categs = Reference(sheet, min_col=1, min_row=1, max_row=6)

We create a category axis. A category axis is an axis with the data treated as a sequence of non-numerical text labels. In our case, we have text labels representing names of countries.

chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)

We create a bar chart and set its data and categories.

chart.legend = None
chart.y_axis.majorGridlines = None

Using the legend and majorGridlines attributes, we turn off the legend and the major grid lines.

chart.varyColors = True

Setting varyColors to True, each bar has a different colour.

chart.title = 'Olympic Gold medals in London'

A title is set for the chart.

sheet.add_chart(chart, 'A8')

The created chart is added to the sheet with the add_chart method; its top-left corner is placed at the cell A8. We print the number of charts in the sheet.

Bar chart
Figure: Bar chart
$ python create_bar_chart.py
1

Source

openpyxl documentation

In this article we have worked with the openpyxl library. We have read data from Excel files and written data, formulas, images, and charts to Excel files. See also Python XlsxWriter, Python CSV, and Python pandas.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.