Mathew K Analytics

Lesson 4 · Python Libraries

How to Read Excel Files in Python Using the xlrd Library: Step-by-Step Tutorial

xlrd is a Python library for reading Excel files. It is used to extract data from old-style .xls workbooks. xlrd can help with data analysis, automation,…

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 xlrd#

  • xlrd is a Python library for reading Excel files.
  • It is used to extract data from old-style .xls workbooks.
  • xlrd can help with data analysis, automation, and reporting.
  • Typical uses include data migration, spreadsheet parsing, and integration.
  • xlrd is focused only on reading .xls files (Excel 97-2003), not writing or editing.
# First, install xlrd if you do not have it
# On Windows, open Command Prompt and run:
# pip install xlrd
import xlrd
print('xlrd imported!')
xlrd imported!

Core Concepts of xlrd#

  • The main object in xlrd is the Book, representing the Excel file.
  • Each Book contains one or more Sheets.
  • Sheets store rows and columns of cell data.
  • The cell is the basic data unit.
  • You read data using methods attached to Book or Sheet objects.
# Example: Open an Excel .xls file and get the Book object
workbook = xlrd.open_workbook('example.xls')
print('Workbook loaded:', workbook)
Workbook loaded: <xlrd.book.Book object at 0x000001D3C5735160>
# Get all sheet names in the workbook
sheets = workbook.sheet_names()
print('Sheet names:', sheets)
Sheet names: ['Inventory']
# Access a sheet by index
sheet0 = workbook.sheet_by_index(0)
print('First sheet:', sheet0.name)
First sheet: Inventory
# Access a sheet by name
sheet_by_name = workbook.sheet_by_name(sheets[0])
print('Accessed sheet:', sheet_by_name.name)
Accessed sheet: Inventory
# Get number of rows and columns in a sheet
row_count = sheet0.nrows
col_count = sheet0.ncols
print('Rows:', row_count, '| Columns:', col_count)
Rows: 4 | Columns: 3
# Read a single cell value
cell_value = sheet0.cell_value(rowx=0, colx=0)
print('Top left cell:', cell_value)
Top left cell: Product
# Read an entire row as a list
first_row = sheet0.row_values(0)
print('First row values:', first_row)
First row values: ['Product', 'Quantity', 'Unit Price']
# Read an entire column as a list
first_col = sheet0.col_values(0)
print('First column values:', first_col)
First column values: ['Product', 'Laptop', 'Tablet', 'Mouse']
# Loop through all rows and print cell values in the first column
for i in range(sheet0.nrows):
    print(f'Row {i}:', sheet0.cell_value(i, 0))
Row 0: Product
Row 1: Laptop
Row 2: Tablet
Row 3: Mouse
# Read all sheet data into a list of lists
all_data = [sheet0.row_values(row) for row in range(sheet0.nrows)]
print('All data:', all_data)
All data: [['Product', 'Quantity', 'Unit Price'], ['Laptop', 7.0, 999.0], ['Tablet', 15.0, 299.0], ['Mouse', 50.0, 19.0]]
# Read a cell and its type
cell = sheet0.cell(0, 0)
print('Cell value:', cell.value, '| Cell type:', cell.ctype)
Cell value: Product | Cell type: 1
# Filter rows by a value in a specific column
target_value = 'Yes'
filtered_rows = [sheet0.row_values(r) for r in range(sheet0.nrows) if sheet0.cell_value(r, 1) == target_value]
print('Rows where column 1 is Yes:', filtered_rows)
Rows where column 1 is Yes: []
# Skip the header row and read data rows only
for row_num in range(1, sheet0.nrows):
    print('Data row:', sheet0.row_values(row_num))
Data row: ['Laptop', 7.0, 999.0]
Data row: ['Tablet', 15.0, 299.0]
Data row: ['Mouse', 50.0, 19.0]
# Handling missing files: Try to open a file that does not exist
try:
    broken_book = xlrd.open_workbook('missing.xls')
except FileNotFoundError as e:
    print('File not found:', e)
File not found: [Errno 2] No such file or directory: 'missing.xls'
# Handling cell errors: Catch out-of-range errors
try:
    bad_cell = sheet0.cell_value(rowx=999, colx=999)
except IndexError as e:
    print('Cell not found:', e)
Cell not found: list index out of range
# Best practice: Read all sheets in a workbook
for sheet_name in workbook.sheet_names():
    sh = workbook.sheet_by_name(sheet_name)
    print(f'Sheet {sheet_name}: {sh.nrows} rows, {sh.ncols} columns')
Sheet Inventory: 4 rows, 3 columns
# Best practice: Handle all cell types
cell_types = ['empty', 'text', 'number', 'date', 'boolean', 'error']
for r in range(sheet0.nrows):
    for c in range(sheet0.ncols):
        cell = sheet0.cell(r, c)
        print(f'Cell[{r},{c}] type:', cell_types[cell.ctype], '| value:', cell.value)
Cell[0,0] type: text | value: Product
Cell[0,1] type: text | value: Quantity
Cell[0,2] type: text | value: Unit Price
Cell[1,0] type: text | value: Laptop
Cell[1,1] type: number | value: 7.0
Cell[1,2] type: number | value: 999.0
Cell[2,0] type: text | value: Tablet
Cell[2,1] type: number | value: 15.0
Cell[2,2] type: number | value: 299.0
Cell[3,0] type: text | value: Mouse
Cell[3,1] type: number | value: 50.0
Cell[3,2] type: number | value: 19.0
# Mini-project: Print summary stats for every sheet
def summarize_xls(path):
    wb = xlrd.open_workbook(path)
    for sheet in wb.sheets():
        print('Sheet:', sheet.name)
        print('Rows:', sheet.nrows, 'Cols:', sheet.ncols)
        print('First row:', sheet.row_values(0))
        print('---')

summarize_xls('example.xls')
Sheet: Inventory
Rows: 4 Cols: 3
First row: ['Product', 'Quantity', 'Unit Price']
---

Thank you for learning xlrd!#

  • If you found this tutorial helpful, please subscribe for more.
  • Like this video and comment with your questions.

Found this useful?

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