ZetCode

Python xlsxwriter

last modified November 29, 2026 Python 3.15

In this article we show how to create Excel files in Python with the xlsxwriter library.

XLSX is the spreadsheet format of Microsoft Excel 2007 and later. An XLSX file is a ZIP archive of XML documents defined by the Office Open XML standard; LibreOffice Calc, Google Sheets, and other spreadsheet programs open it as well.

xlsxwriter is a library for writing XLSX files. It supports text, numbers, formulas, formatting, merged cells, tables, conditional formatting, charts, and images. It can only create new files; it cannot read or modify existing ones. For that, use openpyxl, which we also use in this article to check the files we create. The examples use xlsxwriter 3.3 and openpyxl 3.1.

$ pip install xlsxwriter openpyxl

The first workbook

A workbook is the spreadsheet file and a worksheet is one sheet in it. The first program writes two cells.

first.py
import xlsxwriter

wb = xlsxwriter.Workbook('first.xlsx')
ws = wb.add_worksheet()

ws.write('A1', 'Hello there!')
ws.write(2, 0, 123)

wb.close()

The Workbook constructor takes the file name. The add_worksheet method adds a sheet; without a name, the sheets are called Sheet1, Sheet2, and so on. The write method accepts a cell in the A1 notation or a zero-based row and column, so (2, 0) is cell A3. The file is written when the workbook is closed; a workbook that is not closed produces no file.

$ python first.py
$ file first.xlsx
first.xlsx: Microsoft Excel 2007+

Reading the result

To see what the examples write, we use a short program that prints all non-empty cells of a workbook with openpyxl.

show.py
import sys

from openpyxl import load_workbook

wb = load_workbook(sys.argv[1])

for ws in wb:
    print(f'[{ws.title}] {ws.dimensions}')

    for row in ws.iter_rows():
        for cell in row:
            if cell.value is not None:
                print(f'{cell.coordinate}: {cell.value!r}')

The program iterates over the worksheets and their rows. The dimensions attribute is the range of used cells. Each cell is printed with its coordinate and the repr of its value, so we can tell text from numbers.

$ python show.py first.xlsx
[Sheet1] A1:A3
A1: 'Hello there!'
A3: 123

Data types

The write method picks the cell type from the Python type of the value. There are also specific methods such as write_string, write_number, write_boolean, write_datetime, and write_formula.

data_types.py
from datetime import date

import xlsxwriter

with xlsxwriter.Workbook('types.xlsx') as wb:
    ws = wb.add_worksheet('Types')
    date_format = wb.add_format({'num_format': 'yyyy-mm-dd'})

    ws.write('A1', 'an old falcon')
    ws.write('A2', 42)
    ws.write('A3', 3.14)
    ws.write('A4', True)
    ws.write('A5', date(2026, 11, 29), date_format)
    ws.write('A6', '=A2*2')
    ws.write('A7', '0042')
    ws.write_number('A8', int('0042'))

The workbook is used as a context manager, which closes it at the end of the with block. Excel stores dates as numbers, so a date needs a number format to be displayed as a date; the format is created with add_format and passed as the last argument. A string that starts with an equals sign is written as a formula. Other strings stay strings, even when they look like numbers, so '0042' keeps its leading zeros; to store the number, we convert it and call write_number. openpyxl reads the date back as a datetime, because a spreadsheet cell has no separate date type.

$ python data_types.py
$ python show.py types.xlsx
[Types] A1:A8
A1: 'an old falcon'
A2: 42
A3: 3.14
A4: True
A5: datetime.datetime(2026, 11, 29, 0, 0)
A6: '=A2*2'
A7: '0042'
A8: 42

Rows and columns

The write_row and write_column methods write a sequence of values starting at a cell.

rows_columns.py
import xlsxwriter

header = ['City', 'Country', 'Population']
cities = [
    ('Bratislava', 'Slovakia', 475503),
    ('Budapest', 'Hungary', 1686222),
    ('Prague', 'Czechia', 1384732),
    ('Vienna', 'Austria', 2028399),
]

with xlsxwriter.Workbook('cities.xlsx') as wb:
    ws = wb.add_worksheet('Cities')

    ws.write_row(0, 0, header)

    for row, city in enumerate(cities, start=1):
        ws.write_row(row, 0, city)

    ws.write_column('E1', ['Rank', 3, 1, 2, 4])
    ws.set_column('A:B', 12)
    ws.set_column('C:C', 11)

Each city tuple is written as one row. The enumerate function starts at one because row zero holds the header. The write_column call fills column E from top to bottom. The set_column method sets the width of a range of columns in characters.

$ python rows_columns.py
$ python show.py cities.xlsx
[Cities] A1:E5
A1: 'City'
B1: 'Country'
C1: 'Population'
E1: 'Rank'
A2: 'Bratislava'
B2: 'Slovakia'
C2: 475503
E2: 3
A3: 'Budapest'
B3: 'Hungary'
C3: 1686222
E3: 1
A4: 'Prague'
B4: 'Czechia'
C4: 1384732
E4: 2
A5: 'Vienna'
B5: 'Austria'
C5: 2028399
E5: 4

Formulas

The write_formula method writes an Excel formula. The cell references in the formula use the A1 notation, so the one-based row number is row + 1.

formulas.py
import xlsxwriter

items = [('Keyboard', 2, 39.90), ('Mouse', 3, 19.50), ('Monitor', 1, 229.0)]

with xlsxwriter.Workbook('order.xlsx') as wb:
    ws = wb.add_worksheet('Order')
    ws.write_row('A1', ['Item', 'Quantity', 'Price', 'Total'])

    for row, (name, qty, price) in enumerate(items, start=1):
        ws.write_row(row, 0, [name, qty, price])
        ws.write_formula(row, 3, f'=B{row + 1}*C{row + 1}')

    last = len(items) + 1
    ws.write(last, 2, 'Sum')
    ws.write_formula(last, 3, f'=SUM(D2:D{last})')

xlsxwriter does not calculate formulas. It stores the formula with a result of zero, and the spreadsheet application computes the values when it opens the file. openpyxl reads the formulas as strings. If a program needs the result without a spreadsheet application, it can compute the value in Python and pass it as the optional value argument of write_formula.

$ python formulas.py
$ python show.py order.xlsx
[Order] A1:D5
A1: 'Item'
B1: 'Quantity'
C1: 'Price'
D1: 'Total'
A2: 'Keyboard'
B2: 2
C2: 39.9
D2: '=B2*C2'
A3: 'Mouse'
B3: 3
C3: 19.5
D3: '=B3*C3'
A4: 'Monitor'
B4: 1
C4: 229
D4: '=B4*C4'
C5: 'Sum'
D5: '=SUM(D2:D4)'

Formats

The add_format method creates a Format object from a dictionary of properties: font, colours, alignment, borders, and number format. A format is passed as the last argument of the write methods.

formats.py
import xlsxwriter

items = [('Keyboard', 2, 39.90), ('Mouse', 3, 19.50), ('Monitor', 1, 229.0)]

with xlsxwriter.Workbook('invoice.xlsx') as wb:
    ws = wb.add_worksheet('Invoice')

    header = wb.add_format({'bold': True, 'bg_color': '#DDEBF7',
                            'bottom': 1})
    money = wb.add_format({'num_format': '#,##0.00 €'})
    total = wb.add_format({'bold': True, 'num_format': '#,##0.00 €',
                           'top': 2})

    ws.set_column('A:A', 14)
    ws.set_column('B:D', 11)
    ws.write_row('A1', ['Item', 'Quantity', 'Price', 'Total'], header)

    for row, (name, qty, price) in enumerate(items, start=1):
        ws.write_row(row, 0, [name, qty])
        ws.write(row, 2, price, money)
        ws.write_formula(row, 3, f'=B{row + 1}*C{row + 1}', money)

    last = len(items) + 1
    ws.write(last, 0, 'Total', wb.add_format({'bold': True, 'top': 2}))
    ws.write_blank(last, 1, None, wb.add_format({'top': 2}))
    ws.write_blank(last, 2, None, wb.add_format({'top': 2}))
    ws.write_formula(last, 3, f'=SUM(D2:D{last})', total)

The header is bold with a light blue background and a bottom border. The num_format property sets how numbers are displayed; the value in the cell stays a plain number. The top border of style 2 is a medium line above the total row. The write_blank method writes an empty cell with a format, so the border spans the whole row.

Invoice with formats
Figure: Invoice with formats

Merging cells

The merge_range method merges a range of cells into one and writes a value into it.

merge.py
import xlsxwriter

with xlsxwriter.Workbook('schedule.xlsx') as wb:
    ws = wb.add_worksheet('Schedule')

    title = wb.add_format({'bold': True, 'font_size': 14, 'align': 'center',
                           'valign': 'vcenter', 'bg_color': '#FCE4D6',
                           'border': 1})
    day = wb.add_format({'bold': True, 'align': 'center', 'border': 1})
    cell = wb.add_format({'border': 1})

    ws.set_column('A:E', 12)
    ws.set_row(0, 28)
    ws.merge_range('A1:E1', 'Weekly schedule', title)
    ws.write_row('A2', ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], day)
    ws.merge_range('A3:C3', 'Workshop', cell)
    ws.merge_range('D3:E3', 'Code review', cell)
    ws.write_row('A4', ['Gym', '', 'Gym', '', 'Gym'], cell)

The title spans the five columns of the first row; it is centred horizontally and vertically in a row made higher with set_row. The workshop takes three days and the code review two. A merged range needs a format to show its border, so each range gets one.

Merged cells
Figure: Merged cells

Tables

An Excel table is a named range with a header row, a style, filter buttons, and an optional total row. The add_table method creates one.

table.py
import xlsxwriter

data = [
    ['Apples', 120, 140, 160],
    ['Pears', 80, 95, 70],
    ['Plums', 60, 75, 90],
    ['Grapes', 110, 90, 130],
]

with xlsxwriter.Workbook('fruit.xlsx') as wb:
    ws = wb.add_worksheet('Fruit')
    ws.set_column('A:E', 12)

    ws.add_table('A1:E6', {
        'data': data,
        'style': 'Table Style Medium 2',
        'total_row': True,
        'columns': [
            {'header': 'Fruit', 'total_string': 'Total'},
            {'header': 'January', 'total_function': 'sum'},
            {'header': 'February', 'total_function': 'sum'},
            {'header': 'March', 'total_function': 'sum'},
            {'header': 'Average',
             'formula': '=AVERAGE(Table1[@[January]:[March]])',
             'format': wb.add_format({'num_format': '0.0'})},
        ],
    })

The columns list sets the headers and the per-column options. The total_function option adds a SUBTOTAL formula to the total row. The formula option fills a calculated column; the @ structured reference means the current row of the table, which xlsxwriter expands to [#This Row].

$ python table.py
$ python show.py fruit.xlsx
[Fruit] A1:E6
A1: 'Fruit'
B1: 'January'
C1: 'February'
D1: 'March'
E1: 'Average'
A2: 'Apples'
B2: 120
C2: 140
D2: 160
E2: '=AVERAGE(Table1[[#This Row],[January]:[March]])'
A3: 'Pears'
B3: 80
C3: 95
D3: 70
E3: '=AVERAGE(Table1[[#This Row],[January]:[March]])'
A4: 'Plums'
B4: 60
C4: 75
D4: 90
E4: '=AVERAGE(Table1[[#This Row],[January]:[March]])'
A5: 'Grapes'
B5: 110
C5: 90
D5: 130
E5: '=AVERAGE(Table1[[#This Row],[January]:[March]])'
A6: 'Total'
B6: '=SUBTOTAL(109,[January])'
C6: '=SUBTOTAL(109,[February])'
D6: '=SUBTOTAL(109,[March])'

Conditional formatting

Conditional formatting changes the look of cells based on their values. The conditional_format method applies a rule to a range.

conditional.py
import xlsxwriter

scores = [
    ('Anna', 92, 78, 85), ('Boris', 45, 66, 51), ('Clara', 73, 88, 95),
    ('David', 58, 39, 62), ('Eva', 81, 90, 70),
]

with xlsxwriter.Workbook('scores.xlsx') as wb:
    ws = wb.add_worksheet('Scores')
    ws.set_column('A:D', 10)
    ws.write_row('A1', ['Student', 'Math', 'Physics', 'Chemistry'],
                 wb.add_format({'bold': True}))

    for row, record in enumerate(scores, start=1):
        ws.write_row(row, 0, record)

    ws.conditional_format('B2:D6', {
        'type': 'cell', 'criteria': '<', 'value': 50,
        'format': wb.add_format({'font_color': '#9C0006',
                                 'bg_color': '#FFC7CE'}),
    })
    ws.conditional_format('B2:D6', {'type': 'data_bar',
                                    'bar_color': '#63BE7B'})

The first rule highlights scores below 50 with red text on a light red background. The second rule draws a data bar whose length is proportional to the value. Both rules apply to the same range; the spreadsheet application evaluates them whenever the values change.

Conditional formatting
Figure: Conditional formatting

Charts

The add_chart method creates a chart of a given type, such as column, bar, line, pie, or scatter. The chart gets its data from cell ranges and is placed on a worksheet with insert_chart.

chart.py
import xlsxwriter

data = [
    ['Apples', 120, 140, 160],
    ['Pears', 80, 95, 70],
    ['Plums', 60, 75, 90],
]

with xlsxwriter.Workbook('chart.xlsx') as wb:
    ws = wb.add_worksheet('Sales')
    ws.write_row('A1', ['Fruit', 'January', 'February', 'March'])

    for row, record in enumerate(data, start=1):
        ws.write_row(row, 0, record)

    chart = wb.add_chart({'type': 'column'})

    for col in range(1, 4):
        chart.add_series({
            'name': ['Sales', 0, col],
            'categories': ['Sales', 1, 0, 3, 0],
            'values': ['Sales', 1, col, 3, col],
        })

    chart.set_title({'name': 'Fruit sales'})
    chart.set_y_axis({'name': 'Kilograms'})
    ws.insert_chart('F1', chart, {'x_scale': 0.9, 'y_scale': 0.9})

Each add_series call adds one month as a data series. The ranges are given as lists of the sheet name and zero-based row and column indexes: the series name is a header cell, the categories are the fruit names in column A, and the values are the cells of the month's column. The chart is inserted at cell F1 and scaled down a little.

Column chart
Figure: Column chart

Images

The insert_image method places a PNG, JPEG, GIF, BMP, or SVG image on a worksheet.

image.py
import xlsxwriter

with xlsxwriter.Workbook('photo.xlsx') as wb:
    ws = wb.add_worksheet('Photo')
    ws.write('A1', 'High Tatras')
    ws.insert_image('A2', 'mountains.jpg',
                    {'x_scale': 0.75, 'y_scale': 0.75,
                     'url': 'https://en.wikipedia.org/wiki/High_Tatras'})

The top left corner of the image is at cell A2. The image is scaled to three quarters of its size, and the url option turns it into a link. Images float above the cells and do not change the size of rows or columns.

Image in a worksheet
Figure: Image in a worksheet

Multiple worksheets

In the last example we read sales from a CSV file and write a workbook with one sheet per region and a summary sheet.

sales.csv
region,product,amount
North,pads,120.5
South,pens,64.0
North,pens,33.25
East,pads,210.0
South,pads,99.9
East,ink,15.75

Each line of the file is one sale with a region, a product, and an amount.

report.py
import csv
from collections import defaultdict

import xlsxwriter

regions = defaultdict(list)

with open('sales.csv', newline='') as f:
    for record in csv.DictReader(f):
        regions[record['region']].append(record)

with xlsxwriter.Workbook('report.xlsx') as wb:
    bold = wb.add_format({'bold': True})
    summary = wb.add_worksheet('Summary')
    summary.write_row('A1', ['Region', 'Total'], bold)

    for i, (region, records) in enumerate(sorted(regions.items()), start=1):
        ws = wb.add_worksheet(region)
        ws.write_row('A1', ['Product', 'Amount'], bold)

        for row, record in enumerate(records, start=1):
            ws.write(row, 0, record['product'])
            ws.write_number(row, 1, float(record['amount']))

        summary.write(i, 0, region)
        summary.write_formula(i, 1, f"=SUM('{region}'!B:B)")

The sales are grouped by region in a defaultdict. The summary sheet is added first, so it is the first tab of the workbook. CSV values are strings, so the amounts are written with write_number after a conversion with float. The summary formulas refer to the other sheets by name; the quotes around the name are needed when it contains spaces and harmless otherwise.

$ python report.py
$ python show.py report.xlsx
[Summary] A1:B4
A1: 'Region'
B1: 'Total'
A2: 'East'
B2: "=SUM('East'!B:B)"
A3: 'North'
B3: "=SUM('North'!B:B)"
A4: 'South'
B4: "=SUM('South'!B:B)"
[East] A1:B3
A1: 'Product'
B1: 'Amount'
A2: 'pads'
B2: 210
A3: 'ink'
B3: 15.75
[North] A1:B3
A1: 'Product'
B1: 'Amount'
A2: 'pads'
B2: 120.5
A3: 'pens'
B3: 33.25
[South] A1:B3
A1: 'Product'
B1: 'Amount'
A2: 'pens'
B2: 64
A3: 'pads'
B3: 99.9

Source

xlsxwriter documentation

In this article we have created Excel XLSX files with xlsxwriter: we have written data of various types, rows and columns, formulas, formats, merged cells, tables, conditional formatting, charts, images, and multiple worksheets. See also Openpyxl tutorial, Python CSV, and Python tablib.

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.