Home » ComputerScience » Writing Excel worksheets using Python XlsxWriter

Writing Excel worksheets using Python XlsxWriter

http://xlsxwriter.readthedocs.io/ (© Copyright 2013-2017, John McNamara)

I want to just say thanks to the author John McNamara for writing this reference.

When I write code I normally start with a task and goal in mind as a finished product. I don’t necessarily set out to become an expert in a particular module, but I do want to apply the features of the module to achieve my goals. In the case of the linked article, I can do just that. There are loads of examples and a table of contents that allow me to review a particular feature along with very easy-to-read examples on how to implement.

So for today, I just wanted to learn how to open/create a worksheet and write data to it.

In the future, my requirements will be more complicated and I’ll have this wonderful document to reference each feature I’ll want to incorporate. Eventually, the more I use Python to write Excel spreadsheets, the more of an expert I’ll be at using this module.

Easiest example ever:

#!/usr/bin/env python
import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

# Some data we want to write to the worksheet.
expenses = (
['Rent', 1000],
['Gas', 100],
['Food', 300],
['Gym', 50],
)

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.
worksheet.write(row,col,"ITEM", bold)
worksheet.write(row,col + 1,"COST", bold)
row = row +1

for item, cost in (expenses):
worksheet.write(row, col, item)
worksheet.write(row, col + 1, cost)
row += 1

# Write a total using a formula.
worksheet.write(row, 0, 'Total', bold)
worksheet.write(row, 1, '=SUM(B1:B4)')

workbook.close()
exit(0)

Leave a Reply