How To Read Excel File In Python

5 min read

Reading an Excel file in Python is one of the most common ways to turn spreadsheet data into data you can analyze, clean, and visualize. Whether you are working with sales reports, student records, financial data, inventory lists, or survey results, Python gives you powerful tools for opening Excel files, extracting the data you need, and preparing it for further processing.

Introduction: Why Read Excel Files in Python?

Excel is still widely used in businesses, schools, research, and personal productivity because it is familiar and easy to organize. That said, Excel files are not ideal for large-scale analysis, automation, reporting, or repeated data processing. Python solves this problem by allowing you to read Excel data programmatically.

The most popular and powerful library for this task is pandas. Even so, it is the de facto standard for data manipulation and analysis in Python. With just a few lines of code, pandas can read an entire Excel file into a DataFrame, which is a tabular data structure similar to a spreadsheet or a SQL table And that's really what it comes down to..

Method 1: Using Pandas for Data Analysis

Pandas is ideal when you need to perform data analysis, filtering, aggregation, or visualization. Its read_excel() function is incredibly versatile.

Basic Example:

import pandas as pd

# Read the entire Excel file
df = pd.read_excel('sales_report.xlsx')

# Display the first few rows
print(df.head())

By default, read_excel() reads the first sheet. Because of that, you can specify a sheet by its name or index:

# Read a specific sheet by name
df = pd. read_excel('company_data.

# Read a specific sheet by index (0-based)
df = pd.read_excel('company_data.xlsx', sheet_name=1)

Pandas can also handle files with multiple sheets, reading them into a dictionary of DataFrames:

# Read all sheets into a dictionary
all_sheets = pd.read_excel('company_data.xlsx', sheet_name=None)
# Access a sheet like this: all_sheets['Q3_Sales']

Method 2: Using openpyxl for Cell-Level Control

While pandas is great for analysis, sometimes you need to interact with the Excel file at a more granular level—like modifying cell formatting, formulas, or charts. For this, openpyxl is the library of choice. It allows you to read and write Excel files with precision.

Example: Reading Cell Values and Formatting

from openpyxl import load_workbook

# Load the workbook
wb = load_workbook('simple_data.xlsx')
ws = wb.active  # Get the active sheet

# Access data cell-by-cell
for row in ws.iter_rows(min_row=1, max_row=3, values_only=True):
    print(row)

# Read a specific cell
cell = ws['B2']
print(f"Value in B2: {cell.value}")

Method 3: Using xlrd for Legacy Files

For older .xls files (Excel 97-2003 format), the xlrd library is necessary, as pandas and openpyxl primarily support the newer .xlsx format.

import xlrd

# Open the workbook
workbook = xlrd.open_workbook('legacy_data.xls')
sheet = workbook.sheet_by_index(0)

# Iterate through rows
for row_idx in range(sheet.nrows):
    row_values = sheet.row_values(row_idx)
    print(row_values)

Handling Common Challenges

Real-world Excel files are often messy. Here are tips for common issues:

  • Skipping Headers or Footers: Use the skiprows or nrows parameters in pandas.
  • Handling Merged Cells: Pandas may not handle merged cells gracefully. You might need to preprocess the file or use openpyxl to unmerge them.
  • Dealing with Multiple Header Rows: You can specify the header parameter in pd.read_excel() to set the correct row as the column names.

Conclusion

Python transforms static Excel files into dynamic, analyzable data. Now, the choice of tool depends on your goal: use pandas for swift data analysis, openpyxl for precise formatting and modification, and xlrd for legacy files. By integrating these libraries into your workflow, you move beyond manual spreadsheet tasks and tap into the full potential of your data for informed decision-making Still holds up..

Best Practices for Reliable Excel Processing

When working with Excel files in Python, especially in business or production environments, consistency matters. A few simple habits can prevent many common problems Easy to understand, harder to ignore..

Keep the Original File Safe

Avoid overwriting source files directly. Instead, create cleaned or processed versions with new filenames.

import shutil

source_file = "raw_sales.xlsx"
backup_file = "raw_sales_backup.xlsx"

shutil.copyfile(source_file, backup_file)

This protects your original data from accidental corruption and makes your workflow easier to reproduce That's the part that actually makes a difference..

Use Clear File Names

Instead of naming files like final.xlsx, final2.xlsx, or updated_new.xlsx, use descriptive names with dates or versions Worth keeping that in mind..

sales_q3_2024.xlsx
sales_q3_2024_cleaned.xlsx
sales_q3_2024_report.xlsx

This makes it easier to track changes, share files, and avoid overwriting important versions Practical, not theoretical..

Specify Data Types When Needed

Excel files often contain mixed data types. Still, for example, a column may contain dates, numbers, and text in the same column. You can use dtype to control how pandas reads certain columns.

df = pd.read_excel(
    "customer_data.xlsx",
    dtype={"Customer ID": "string", "Phone": "string"}
)

This is especially useful for IDs, ZIP codes, phone numbers, and account numbers, where leading zeros may matter Nothing fancy..

Parse Dates Correctly

Excel date values can sometimes be interpreted inconsistently. You can explicitly tell pandas which columns contain dates.

df = pd.read_excel(
    "orders.xlsx",
    parse_dates=["Order Date", "Ship Date"]
)

After parsing, you can perform date-based analysis such as filtering by quarter, calculating delivery times, or grouping sales by month Worth keeping that in mind..


Writing Results Back to Excel

After analyzing or cleaning data, you may want to save the results back into an Excel workbook.

Using pandas, you can write a DataFrame to an Excel file:

df.to_excel("cleaned_sales.xlsx", index=False)

If you want to write multiple DataFrames into the same workbook, use ExcelWriter:

with pd.ExcelWriter("monthly_report.xlsx", engine="openpyxl") as writer:
    sales_summary.to_excel(writer, sheet_name="Sales Summary", index=False)
    regional_performance.to_excel(writer, sheet_name="Regional Performance", index=False)
    top_products.to_excel(writer, sheet_name="Top Products", index=False)

This is useful for generating structured reports automatically.


Adding Formatting with openpyxl

While pandas is excellent for data handling, formatting is often better managed with openpyxl.

Here's one way to look at it: you can style headers, freeze rows, adjust column widths, and apply conditional formatting.

from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment

wb = load_workbook("cleaned
Out the Door

Brand New Reads

Keep the Thread Going

Up Next

Thank you for reading about How To Read Excel File In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home