5 Best Ways to Create and Write an Excel File Using the XlsxWriter Module in Python

πŸ’‘ Problem Formulation: Python’s XlsxWriter module enables users to create and manipulate Excel files programmatically. However, users may struggle with varying requirements for data representation. This article demonstrates how to create and write data to an Excel file using XlsxWriter, with an input being a data structure in Python (such as a list, dictionary, etc.) and the desired output being a well-formatted Excel spreadsheet.

Method 1: Creating a Simple Worksheet

This method involves initializing a workbook and worksheet using XlsxWriter to create a basic Excel file. Users can add text, numbers, formulas, and more to the spreadsheet.

β™₯️ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month

Here’s an example:

import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()

# 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.
for item, cost in expenses:
    worksheet.write(row, col, item)
    worksheet.write(row, col + 1, cost)
    row += 1

# Close the workbook
workbook.close()

The output of this code snippet is an Excel file named ‘Expenses01.xlsx’ with two columns representing the item and its cost.

This snippet performs the basic operation of creating an Excel file and writes a list of expenses row by row. The data is organized in two columns, corresponding to the simple structure of each tuple in the list. It’s a straightforward approach for writing data to an Excel file.

Method 2: Formatting Cells

Users can apply formatting to cells in a spreadsheet created with XlsxWriter. This method outlines how to format text, backgrounds, and more to enhance the visual presentation.

Here’s an example:

import xlsxwriter

workbook = xlsxwriter.Workbook('Expenses02.xlsx')
worksheet = workbook.add_worksheet()

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some data headers.
worksheet.write('A1', 'Item', bold)
worksheet.write('B1', 'Cost', bold)

expenses = (
    ['Rent', 1000],
    ['Gas', 100],
    ['Food', 300],
    ['Gym', 50],
)

# Start writing data after headers.
row = 1
col = 0

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

workbook.close()

The output is an Excel file named “Expenses02.xlsx” with headers ‘Item’ and ‘Cost’ in bold formatting.

This snippet builds upon the first method by adding cell formatting. With XlsxWriter, cell formatting can include fonts, colors, borders, and more. In this example, the headers “Item” and “Cost” are bolded, which improves the readability of the spreadsheet.

Method 3: Adding Formulas

XlsxWriter can also be used to add formulas to a spreadsheet. This is done by referencing cell coordinates within a formula string that the module interprets and writes to a given cell.

Here’s an example:

import xlsxwriter

workbook = xlsxwriter.Workbook('Expenses03.xlsx')
worksheet = workbook.add_worksheet()

expenses = (
    ['Rent', 1000],
    ['Gas', 100],
    ['Food', 300],
    ['Gym', 50],
)

row = 0
col = 0

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')
worksheet.write(row, 1, '=SUM(B1:B4)')

workbook.close()

The output is an Excel file named “Expenses03.xlsx” with data similar to previous examples but also includes a ‘Total’ cell with a formula that calculates the sum of the expenses.

This code snippet goes further by incorporating a formula to calculate the total of expenses. The ‘=SUM(B1:B4)’ formula, written in the last row after the expenses, totals the cost column. This illustrates XlsxWriter’s effectiveness for a dynamic spreadsheet creation.

Method 4: Working with Charts

XlsxWriter supports the creation of charts within Excel files. This method will demonstrate how to create a chart based on data in a worksheet.

Here’s an example:

import xlsxwriter

workbook = xlsxwriter.Workbook('Expenses04.xlsx')
worksheet = workbook.add_worksheet()

# Some sample data for the chart.
expenses = (
    ['Rent', 1000],
    ['Gas', 100],
    ['Food', 300],
    ['Gym', 50],
)

row = 0
col = 0

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

# Create a new chart object.
chart = workbook.add_chart({'type': 'column'})

# Configure the chart from the spreadsheet data we've already written.
# This uses a list of dicts to set a series of data points.
chart.add_series({
    'categories': '=Sheet1!$A$1:$A$4',
    'values':     '=Sheet1!$B$1:$B$4',
})

worksheet.insert_chart('D2', chart)

workbook.close()

The output is an Excel file named “Expenses04.xlsx” with an embedded column chart displaying the expenses data.

In this example, a chart is created showing the breakdown of expenses visually. After entering the data, a chart object is added to the workbook, and the data for the chart is set by referencing the cells containing the information. The chart is then inserted into the workbook at the specified location. This method highlights how one can incorporate visual analysis tools into their spreadsheets using XlsxWriter.

Bonus One-Liner Method 5: Using List Comprehensions

Python’s list comprehensions can be used along with the XlsxWriter module for a more compact way of writing data to cells.

Here’s an example:

import xlsxwriter

workbook = xlsxwriter.Workbook('Expenses05.xlsx')
worksheet = workbook.add_worksheet()

expenses = [
    ['Rent', 1000],
    ['Gas', 100],
    ['Food', 300],
    ['Gym', 50],
]

[worksheet.write(row, col, item) for row, (item, cost) in enumerate(expenses) for col in (0, 1) if not col or worksheet.write(row, col, cost)]

workbook.close()

The output is an Excel file named “Expenses05.xlsx” that contains the same expenses data as previous examples.

The code snippet leverages the compact syntax of list comprehensions to write both items and costs to the worksheet in a single statement. It demonstrates Python’s powerful inline iteration capabilities and provides a concise alternative to traditional for loops.

Summary/Discussion

  • Method 1: Creating a Simple Worksheet. Strengths: Simplicity and ease of use. Suitable for straightforward data writing scenarios. Weaknesses: No cell formatting or advanced features.
  • Method 2: Formatting Cells. Strengths: Enhances visual appearance and readability. Allows cell-level customization. Weaknesses: Only focuses on formatting; doesn’t deal with complex data structures.
  • Method 3: Adding Formulas. Strengths: Enables automation of calculations within the spreadsheet. Weaknesses: Requires understanding of Excel formula syntax. May become complex with advanced formulas.
  • Method 4: Working with Charts. Strengths: Allows visual data presentation directly within the spreadsheet. Supports multiple chart types. Weaknesses: More complex syntax. Takes more code to set up compared to simple data writing.
  • Method 5: Using List Comprehensions. Strength: Compact and elegant code for simple data entries. Weakness: Can be less readable, especially for users not familiar with Python list comprehensions.