Mathew K Analytics

Lesson 6 · Python Libraries

Comprehensive Guide to Using Python xlsxwriter for Excel File Creation and Automation

xlsxwriter is a Python library for creating Excel .xlsx files. It is used for writing, formatting and customizing Excel spreadsheets. Real-world uses…

XlsxWriter

What you'll learn

Datasets used in this lesson

Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.

📓 Full notebook

Download .ipynb

Introduction to xlsxwriter#

  • xlsxwriter is a Python library for creating Excel .xlsx files.
  • It is used for writing, formatting and customizing Excel spreadsheets.
  • Real-world uses include generating reports, exporting data, and automating spreadsheet creation.
  • You do not need to have Excel installed to create .xlsx files.
  • It supports advanced Excel features like formulas, charts, and formatting.
# Install xlsxwriter using pip if needed
# pip install xlsxwriter
import xlsxwriter

Core Concepts in xlsxwriter#

  • The Workbook object is the Excel file you create.
  • The Worksheet object is a single sheet inside your Excel file.
  • Format objects let you style your cells.
  • You use methods like write() and write_row() to add data.
print('Let us create a new Excel file using xlsxwriter.')
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
print('Created a new workbook and one sheet.')
Let us create a new Excel file using xlsxwriter.
Created a new workbook and one sheet.
worksheet.write('A1', 'Hello World')
print('Wrote Hello World to cell A1.')
Wrote Hello World to cell A1.
workbook.close()
print('Saved and closed the Excel file.')
Saved and closed the Excel file.
workbook = xlsxwriter.Workbook('numbers.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 123)
worksheet.write('A2', 456.78)
worksheet.write('A3', 'Text in a cell')
workbook.close()
workbook = xlsxwriter.Workbook('row_and_col.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, 'Top left cell')
worksheet.write(1, 2, 100)
workbook.close()
workbook = xlsxwriter.Workbook('multiple_sheets.xlsx')
worksheet1 = workbook.add_worksheet('Data')
worksheet2 = workbook.add_worksheet('Summary')
worksheet1.write('A1', 'Data sheet here!')
worksheet2.write('A1', 'Summary sheet here!')
workbook.close()
workbook = xlsxwriter.Workbook('formatted.xlsx')
worksheet = workbook.add_worksheet()
bold_format = workbook.add_format({'bold': True})
worksheet.write('A1', 'Bold text', bold_format)
worksheet.write('A2', 'Normal text')
workbook.close()
workbook = xlsxwriter.Workbook('column_width.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 30)
worksheet.write('A1', 'Column width set to 30.')
workbook.close()
workbook = xlsxwriter.Workbook('write_row_col.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_row('A1', [1, 2, 3, 4])
worksheet.write_column('B2', ['a', 'b', 'c'])
workbook.close()
workbook = xlsxwriter.Workbook('formula.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 10)
worksheet.write('A2', 20)
worksheet.write_formula('A3', '=A1+A2')
workbook.close()
workbook = xlsxwriter.Workbook('conditional.xlsx')
worksheet = workbook.add_worksheet()
for i in range(1, 11):
    worksheet.write(i, 0, i)
worksheet.conditional_format('A2:A11', {'type': '3_color_scale'})
workbook.close()
workbook = xlsxwriter.Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
for row, value in enumerate([10, 40, 50, 20, 10]):
    worksheet.write(row, 0, value)
chart = workbook.add_chart({'type': 'column'})
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
worksheet.insert_chart('C1', chart)
workbook.close()
workbook = xlsxwriter.Workbook('image.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Insert an image below:')
worksheet.insert_image('A3', 'mat-analytics.png')
workbook.close()
try:
    import xlsxwriter
    print('xlsxwriter is installed.')
except ImportError:
    print('Error: xlsxwriter is not installed! Install it with pip.')
xlsxwriter is installed.
try:
    workbook = xlsxwriter.Workbook('/invalid_path/fail.xlsx')
    workbook.add_worksheet().write('A1', 'Should not work')
    workbook.close()
except Exception as e:
    print('Caught error:', e)
Caught error: [Errno 2] No such file or directory: '/invalid_path/fail.xlsx'
try:
    workbook = xlsxwriter.Workbook('readonly.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', 'Test Readonly')
    workbook.close()
    # Simulate read-only error by deleting file then writing again
    import os
    os.chmod('readonly.xlsx', 0o444)  # Make read-only
    workbook = xlsxwriter.Workbook('readonly.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', 'Write to readonly')
    workbook.close()
except Exception as e:
    print('Caught expected error writing to read-only file:', e)
finally:
    import os
    os.chmod('readonly.xlsx', 0o666)  # Reset permissions
Caught expected error writing to read-only file: [Errno 13] Permission denied: 'readonly.xlsx'

Best Practices and Common Patterns with xlsxwriter#

  • Close all workbooks using workbook.close() to save your files.
  • Use with open('fname.xlsx', 'rb') as f: to read output files.
  • Reuse format objects to save memory and speed up your code.
  • Always handle exceptions for file paths and permissions.
  • Create functions to handle repeated tasks.
def make_simple_report(filename, data):
    workbook = xlsxwriter.Workbook(filename)
    worksheet = workbook.add_worksheet()
    worksheet.write_row('A1', ['Name', 'Score'])
    for row, (name, score) in enumerate(data, start=1):
        worksheet.write_row(row, 0, [name, score])
    workbook.close()
    print(f'Report saved to {filename}')
sample_data = [('Alice', 90), ('Bob', 78), ('Carla', 85)]
make_simple_report('scores.xlsx', sample_data)
Report saved to scores.xlsx
# Mini-project: Export a multiplication table as Excel
def multiplication_table(n, filename):
    workbook = xlsxwriter.Workbook(filename)
    worksheet = workbook.add_worksheet()
    # Write header row
    worksheet.write_row(0, 1, list(range(1, n+1)))
    # Write header column and table values
    for i in range(1, n+1):
        worksheet.write(i, 0, i)
        worksheet.write_row(i, 1, [i*j for j in range(1, n+1)])
    workbook.close()
    print(f'Multiplication table saved to {filename}')

multiplication_table(10, 'multiplication_table.xlsx')
Multiplication table saved to multiplication_table.xlsx

Thank you for watching!#

  • Like and subscribe for more Python tutorials.
  • Comment below on what you want to learn next.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.