Of course! Let's dive deep into xlswriter, a powerful and popular Python library for creating Excel files.

What is xlswriter?
xlswriter is a Python module that allows you to create spreadsheet files (.xlsx) with formatting, multiple sheets, charts, and images. Its key strengths are:
- High Performance: It's written for speed and can generate very large files efficiently.
- Rich Formatting: You can apply a wide range of Excel formatting options, like fonts, colors, borders, number formats, and cell merging.
- Easy to Use: The API is straightforward and intuitive.
- No Excel Dependency: It does not require Microsoft Excel to be installed on the machine where the script is running.
Installation
First, you need to install the library. It's available on PyPI, so you can use pip:
pip install XlsxWriter
Basic Usage: Creating a Simple Workbook
Let's start with the most basic example: creating a workbook with a single sheet and writing some data.
import xlsxwriter
# 1. Create a new Excel file and a worksheet object.
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet = workbook.add_worksheet('Sheet1')
# 2. Write some data to the worksheet.
# The syntax is worksheet.write(row, column, data)
# Note: Rows and columns are ZERO-indexed.
worksheet.write('A1', 'Hello') # Write to cell A1
worksheet.write('B1', 'World!') # Write to cell B1
worksheet.write(2, 0, 42) # Write to cell A3 (row 2, col 0)
worksheet.write(2, 1, 3.14159) # Write to cell B3 (row 2, col 1)
worksheet.write(3, 0, 'Date') # Write to cell A4
worksheet.write(3, 1, '2025-10-27') # Write to cell B4
# 3. Close the workbook. This is essential to save the file.
workbook.close()
print("Excel file 'output.xlsx' created successfully.")
When you run this code, an output.xlsx file will be created in the same directory. Opening it will show:

| A | B | |
|---|---|---|
| 1 | Hello | World! |
| 2 | ||
| 3 | 42 | 14159 |
| 4 | Date | 2025-10-27 |
Adding Formatting (The Power of xlswriter)
This is where xlswriter truly shines. You create a format object and apply it to cells.
import xlsxwriter
workbook = xlsxwriter.Workbook('formatted_output.xlsx')
worksheet = workbook.add_worksheet()
# --- Create formatting objects ---
# Format 1: Bold text
bold_format = workbook.add_format({'bold': True})
# Format 2: Italic text with a background color
italic_format = workbook.add_format({
'italic': True,
'bg_color': '#FFCC00' # Light yellow
})
# Format 3: Currency format
currency_format = workbook.add_format({'num_format': '$#,##0.00'})
# Format 4: A border
border_format = workbook.add_format({'border': 1})
# --- Apply the formats ---
worksheet.write('A1', 'Product Name', bold_format)
worksheet.write('B1', 'Price', bold_format)
worksheet.write('C1', 'In Stock', bold_format)
worksheet.write('A2', 'Laptop', border_format)
worksheet.write('B2', 1200.50, currency_format)
worksheet.write('C2', 10, border_format)
worksheet.write('A3', 'Mouse', border_format)
worksheet.write('B3', 25.99, currency_format)
worksheet.write('C3', 50, border_format)
worksheet.write('A4', 'Keyboard', border_format)
worksheet.write('B4', 75.00, currency_format)
worksheet.write('C4', 30, border_format)
# --- Adjust column widths for better readability ---
worksheet.set_column('A:A', 20) # Set width of column A to 20 characters
worksheet.set_column('B:B', 15) # Set width of column B to 15 characters
worksheet.set_column('C:C', 12) # Set width of column C to 12 characters
workbook.close()
This will produce a much more professional-looking spreadsheet.
Advanced Features
Writing Formulas
You can write Excel formulas directly into cells by using a string that starts with an .
worksheet.write('A5', 'Total Sales')
worksheet.write('B5', '=SUM(B2:B4)', bold_format)
Merging Cells
To merge a range of cells into one, use the merge_range() method.

merge_format = workbook.add_format({
'bold': True,
'align': 'center',
'valign': 'vcenter'
})
worksheet.merge_range('A1:C1', 'Monthly Sales Report', merge_format)
Adding Charts
xlswriter has excellent built-in support for creating charts.
# (Assuming the 'formatted_output.xlsx' structure from above)
# Create a new workbook for the chart example
chart_workbook = xlsxwriter.Workbook('chart_example.xlsx')
chart_worksheet = chart_workbook.add_worksheet()
# Write the data again
data = [
['Product', 'Sales'],
['Apple', 1000],
['Orange', 800],
['Banana', 1200],
['Mango', 600],
]
for row, data_row in enumerate(data):
for col, item in enumerate(data_row):
chart_worksheet.write(row, col, item)
# --- Create a new chart object ---
chart = chart_workbook.add_chart({'type': 'column'}) # 'column', 'bar', 'line', 'pie', etc.
# --- Configure the series ---
# (category, value)
chart.add_series({
'name': '=Sheet1!$B$1',
'categories': '=Sheet1!$A$2:$A$5',
'values': '=Sheet1!$B$2:$B$5',
})
# --- Add chart title and axis labels ---
chart.set_title({'name': 'Fruit Sales Chart'})
chart.set_x_axis({'name': 'Fruit Type'})
chart.set_y_axis({'name': 'Total Sales'})
# --- Insert the chart into the worksheet ---
# The top-left cell of the chart is E2
chart_worksheet.insert_chart('E2', chart)
chart_workbook.close()
Working with Multiple Sheets
You can easily add and write to multiple sheets within a single workbook.
multi_sheet_workbook = xlsxwriter.Workbook('multi_sheet.xlsx')
# Sheet 1: Q1 Data
q1_sheet = multi_sheet_workbook.add_worksheet('Q1_Sales')
q1_sheet.write('A1', 'Q1 Sales')
q1_sheet.write('A2', 50000)
q1_sheet.write('A3', 75000)
# Sheet 2: Q2 Data
q2_sheet = multi_sheet_workbook.add_worksheet('Q2_Sales')
q2_sheet.write('A1', 'Q2 Sales')
q2_sheet.write('A2', 60000)
q2_sheet.write('A3', 80000)
# Sheet 3: Summary
summary_sheet = multi_sheet_workbook.add_worksheet('Summary')
summary_sheet.write('A1', 'Total Sales')
# You can even reference cells from other sheets!
summary_sheet.write('A2', '=Q1_Sales!A2 + Q2_Sales!A2')
summary_sheet.write('A3', '=Q1_Sales!A3 + Q2_Sales!A3')
multi_sheet_workbook.close()
Comparison with Other Libraries
It's useful to know how xlswriter compares to other common Excel libraries.
| Library | Primary Use Case | Can Read? | Can Write? | Key Feature |
|---|---|---|---|---|
XlsxWriter |
Creating new .xlsx files |
No | Yes | Best-in-class formatting and performance for writing. |
openpyxl |
Reading, writing, and modifying existing .xlsx files |
Yes | Yes | Great for manipulating existing workbooks. Slower for writing large files than XlsxWriter. |
pandas |
Data analysis and manipulation | Yes | Yes | Uses openpyxl or xlwt under the hood. The df.to_excel() method is very convenient for simple tasks. |
When to choose XlsxWriter:
- When you need to create a new Excel file from scratch.
- When performance and speed are critical (e.g., generating large reports).
- When you need advanced cell formatting, charts, or other features not available in simpler libraries.
When to choose openpyxl:
- When you need to read an existing Excel file and modify it (e.g., update a template, change values).
- When you need to preserve all existing Excel features (like VBA macros, complex pivot tables) in a file you are saving.
When to choose pandas:
- When your data is already in a pandas DataFrame and you just need a quick way to save it to an Excel sheet. It's the most convenient for this specific use case.
