Last modified: Nov 20, 2025 By Alexander Williams

Excel Automation with Python xlrd Examples

Excel automation saves time and reduces errors. Python xlrd makes this easy. It reads Excel files efficiently. This article shows practical examples.

What is Python xlrd?

xlrd is a Python library. It reads data from Excel files. It supports .xls format primarily. It is perfect for legacy Excel files.

The library extracts cell values, formulas, and metadata. It works well for automated reporting. It helps with data processing tasks.

Financial Report Processing

Banks process daily transaction reports. These often come in Excel format. Manual processing takes hours. xlrd automates this completely.

Here is a sample financial report processor. It extracts transaction data. It calculates daily totals automatically.


import xlrd

def process_financial_report(file_path):
    # Open the workbook
    workbook = xlrd.open_workbook(file_path)
    
    # Get the first sheet
    sheet = workbook.sheet_by_index(0)
    
    total_debit = 0
    total_credit = 0
    
    # Process rows (skip header row)
    for row_idx in range(1, sheet.nrows):
        transaction_type = sheet.cell_value(row_idx, 2)
        amount = sheet.cell_value(row_idx, 3)
        
        if transaction_type == "Debit":
            total_debit += amount
        elif transaction_type == "Credit":
            total_credit += amount
    
    return total_debit, total_credit

# Example usage
debit, credit = process_financial_report("daily_transactions.xls")
print(f"Total Debit: ${debit:,.2f}")
print(f"Total Credit: ${credit:,.2f}")

Total Debit: $15,430.50
Total Credit: $12,890.25

This automation saves hours daily. It eliminates manual calculation errors. The results are consistent and reliable.

Inventory Management System

Retail stores manage inventory with Excel. They track stock levels and reorder points. xlrd helps automate inventory checks.

This example reads inventory data. It identifies low stock items. It generates reorder alerts automatically.


import xlrd

def check_inventory_levels(file_path):
    workbook = xlrd.open_workbook(file_path)
    sheet = workbook.sheet_by_index(0)
    
    low_stock_items = []
    
    # Check each product's stock level
    for row_idx in range(1, sheet.nrows):
        product_id = sheet.cell_value(row_idx, 0)
        product_name = sheet.cell_value(row_idx, 1)
        current_stock = sheet.cell_value(row_idx, 2)
        reorder_point = sheet.cell_value(row_idx, 3)
        
        if current_stock <= reorder_point:
            low_stock_items.append({
                'product_id': product_id,
                'product_name': product_name,
                'current_stock': current_stock
            })
    
    return low_stock_items

# Process inventory file
low_stock = check_inventory_levels("inventory.xls")
print("Low Stock Items Requiring Reorder:")
for item in low_stock:
    print(f"ID: {item['product_id']}, Name: {item['product_name']}, Stock: {item['current_stock']}")

Low Stock Items Requiring Reorder:
ID: P10023, Name: Wireless Mouse, Stock: 5
ID: P10045, Name: USB-C Cable, Stock: 3
ID: P10067, Name: Laptop Stand, Stock: 2

This automation prevents stockouts. It ensures timely reordering. It maintains optimal inventory levels.

Employee Attendance Tracking

HR departments track employee attendance. Many use Excel timesheets. xlrd automates attendance processing.

This example calculates monthly attendance. It processes timesheet data. It identifies attendance patterns.


import xlrd
from datetime import datetime

def process_attendance(file_path):
    workbook = xlrd.open_workbook(file_path)
    sheet = workbook.sheet_by_index(0)
    
    attendance_data = {}
    
    for row_idx in range(1, sheet.nrows):
        employee_id = sheet.cell_value(row_idx, 0)
        date = xlrd.xldate_as_datetime(sheet.cell_value(row_idx, 1), workbook.datemode)
        hours_worked = sheet.cell_value(row_idx, 2)
        
        if employee_id not in attendance_data:
            attendance_data[employee_id] = {
                'total_hours': 0,
                'work_days': 0
            }
        
        attendance_data[employee_id]['total_hours'] += hours_worked
        attendance_data[employee_id]['work_days'] += 1
    
    return attendance_data

# Analyze attendance
attendance = process_attendance("monthly_attendance.xls")
print("Monthly Attendance Summary:")
for emp_id, data in attendance.items():
    avg_hours = data['total_hours'] / data['work_days']
    print(f"Employee {emp_id}: {data['work_days']} days, {data['total_hours']} total hours, {avg_hours:.1f} avg hours/day")

Monthly Attendance Summary:
Employee E1001: 22 days, 176.0 total hours, 8.0 avg hours/day
Employee E1002: 20 days, 162.5 total hours, 8.1 avg hours/day
Employee E1003: 21 days, 168.0 total hours, 8.0 avg hours/day

This saves HR significant time. It provides accurate attendance records. It supports payroll processing.

Sales Data Analysis

Sales teams analyze performance data. Excel files contain sales records. xlrd extracts and processes this data.

This example analyzes sales performance. It calculates metrics by region and product. It identifies top performers.


import xlrd

def analyze_sales_performance(file_path):
    workbook = xlrd.open_workbook(file_path)
    sheet = workbook.sheet_by_index(0)
    
    sales_by_region = {}
    product_sales = {}
    
    for row_idx in range(1, sheet.nrows):
        region = sheet.cell_value(row_idx, 1)
        product = sheet.cell_value(row_idx, 2)
        sales_amount = sheet.cell_value(row_idx, 4)
        
        # Track regional sales
        if region not in sales_by_region:
            sales_by_region[region] = 0
        sales_by_region[region] += sales_amount
        
        # Track product sales
        if product not in product_sales:
            product_sales[product] = 0
        product_sales[product] += sales_amount
    
    return sales_by_region, product_sales

# Generate sales report
regional_sales, product_performance = analyze_sales_performance("sales_data.xls")

print("Regional Sales Performance:")
for region, sales in regional_sales.items():
    print(f"{region}: ${sales:,.2f}")

print("\nTop Performing Products:")
for product, sales in sorted(product_performance.items(), key=lambda x: x[1], reverse=True)[:3]:
    print(f"{product}: ${sales:,.2f}")

Regional Sales Performance:
North: $45,230.00
South: $38,150.00
East: $52,890.00
West: $41,670.00

Top Performing Products:
Laptop Pro: $28,450.00
Tablet Plus: $25,680.00
Phone Max: $22,350.00

This automation provides quick insights. It helps sales teams make data-driven decisions. It identifies growth opportunities.

Academic Grade Processing

Educational institutions process student grades. Excel is commonly used for gradebooks. xlrd automates grade calculations.

This example processes student grades. It calculates averages and identifies struggling students. It generates performance reports.


import xlrd

def process_student_grades(file_path):
    workbook = xlrd.open_workbook(file_path)
    sheet = workbook.sheet_by_index(0)
    
    student_grades = {}
    
    for row_idx in range(1, sheet.nrows):
        student_id = sheet.cell_value(row_idx, 0)
        student_name = sheet.cell_value(row_idx, 1)
        assignments = [sheet.cell_value(row_idx, col) for col in range(2, 7)]
        
        # Calculate average, ignoring empty cells
        valid_grades = [grade for grade in assignments if grade != '']
        average = sum(valid_grades) / len(valid_grades) if valid_grades else 0
        
        student_grades[student_id] = {
            'name': student_name,
            'average': average,
            'needs_help': average < 70
        }
    
    return student_grades

# Process gradebook
grades = process_student_grades("student_grades.xls")
print("Student Grade Summary:")
for student_id, data in grades.items():
    status = "Needs Help" if data['needs_help'] else "On Track"
    print(f"{data['name']} (ID: {student_id}): {data['average']:.1f}% - {status}")

Student Grade Summary:
John Smith (ID: S1001): 85.5% - On Track
Maria Garcia (ID: S1002): 68.2% - Needs Help
David Chen (ID: S1003): 92.0% - On Track
Lisa Johnson (ID: S1004): 65.8% - Needs Help

This saves teachers countless hours. It provides timely student performance data. It supports early intervention.

Best Practices for Excel Automation

Follow these practices for successful automation. They ensure reliable and maintainable code.

Always validate input files first. Check file format and structure. Handle exceptions gracefully.

Use the open_workbook function with error handling. Check sheet existence before access. Handle missing data appropriately.

For complex projects, consider migrating from Python xlrd to openpyxl safely. Newer Excel formats may require different tools.

When working with multiple data sources, learn to work with multiple Excel sheets in Python xlrd. This expands your automation capabilities.

For data quality, implement techniques to clean Excel data with Python xlrd. This ensures accurate processing results.

Conclusion

Python xlrd provides powerful Excel automation capabilities. The examples show real-world applications across industries.

Financial reporting, inventory management, and academic grading all benefit. Automation saves time and reduces errors.

Start with simple tasks. Gradually tackle more complex workflows. The time investment pays significant dividends.

Remember that xlrd works best with .xls files. For newer formats, consider alternative libraries. The principles remain the same.

Excel automation with Python transforms business processes. It turns manual tasks into efficient automated workflows. The possibilities are endless.