You can read an Excel file in Python in a few lines by opening it with pandas' read_excel() function, which relies on the openpyxl library under the hood. Install pandas and openpyxl, point pandas at your workbook path, and you get a DataFrame you can inspect, filter and analyse like any other table. The rest of this guide covers picking the right sheet, cleaning up messy headers, handling formulas and dates, and fixing the errors that most commonly stop people in their tracks.

What You'll Need

  • Python 3.8 or newer installed and working from a terminal (python --version should print a version).
  • The pandas library for reading and manipulating tabular data.
  • The openpyxl engine for modern .xlsx and .xlsm files. For old .xls files you also need xlrd.
  • An Excel workbook saved somewhere you can reach from your script, ideally in the same folder as the script or referenced by a full path.
  • Optional but useful: an IDE or editor such as VS Code, Jupyter, or PyCharm for interactive inspection.

Install the core packages from a terminal:

pip install pandas openpyxl

If you use conda, conda install pandas openpyxl works too. On some Linux systems you may need to create a virtual environment first so that pip installs into the right interpreter.

Step-by-Step

  1. Put the workbook where your script can find it. The simplest approach is to place the .xlsx file in the same directory as your Python script and reference it by filename only. Otherwise use an absolute path such as /home/user/data/report.xlsx on Linux/macOS or C:\\Users\\me\\data\\report.xlsx on Windows. In raw Python strings, backslashes are escape characters, so either double them or prefix the string with r to make it a raw string.
  2. Import pandas. Start your script with import pandas as pd. The pd alias is a convention that makes the rest of the code shorter and matches almost every tutorial and reference you will find.
  3. Read the file. Call df = pd.read_excel("report.xlsx"). Pandas opens the first sheet by default, treats the first row as column headers, and returns a DataFrame. You do not need to tell it which engine to use for .xlsx in recent pandas versions, since openpyxl is selected automatically once installed.
  4. Inspect what you got. Run print(df.head()) to see the first five rows, print(df.shape) for row and column counts, and print(df.columns.tolist()) to list the header names. This is the fastest way to confirm the data landed in the shape you expected before you write any analysis code.
  5. Choose a specific sheet. Most real workbooks have several tabs. Pass the sheet name with pd.read_excel("report.xlsx", sheet_name="Sales"), or the zero-based index with sheet_name=1 for the second sheet. Passing sheet_name=None returns a dictionary of all sheets keyed by name, which is handy when you do not know the tab names yet.
  6. Fix messy headers. If your sheet has a title row, a blank row, or notes above the table, the real headers will not be on row one. Use header=2 to treat the third row as the header (pandas is zero-based here), or skiprows=3 to skip the first three rows entirely. Check the result with df.head() after each change.
  7. Select the columns you need. Use usecols to load only certain columns by name or letter range, for example pd.read_excel("report.xlsx", usecols="A:C") or usecols=["Name", "Amount"]. This speeds up large files and cuts memory use. Use dtype to force a column type, such as dtype={"Postcode": str}, when a column of numbers with leading zeros would otherwise lose them.
  8. Handle dates and formulas. Excel dates usually arrive as pandas datetime values when the cell is formatted as a date, but cells stored as plain text stay as strings, so verify with df.dtypes. For formulas, pandas reads the cached value Excel last saved, not the formula itself. A file created by another tool that never calculated formulas may show blanks or zeros. Open and save the workbook in Excel once, or use data_only=True behaviour by loading the workbook with openpyxl directly when you need the displayed values.
  9. Deal with empty rows and totals. Many spreadsheets end with total rows or contain blank separator rows. Inspect df.tail() and either drop them with df.dropna(how="all") or slice them off with df.iloc[:-1]. Never build an analysis straight on a raw read without glancing at the bottom rows.
  10. Save the result. Once the data is clean, export it with df.to_csv("clean.csv", index=False) or df.to_excel("clean.xlsx", index=False). Setting index=False stops pandas writing its row numbers as an extra column, which confuses most downstream tools.

Common Mistakes

Using a relative path from the wrong folder. The working directory of your script is not always the folder the script lives in. When in doubt, print import os; os.getcwd() to see where Python is looking, or use an absolute path.

Forgetting openpyxl. Installing pandas alone is not enough for .xlsx files in many environments, producing a Missing optional dependency 'openpyxl' error. Install both.

Assuming the first sheet is the right one. A hidden summary tab or a cover sheet often sits first. Always check pd.ExcelFile("file.xlsx").sheet_names before trusting a default read.

Expecting formulas to be recalculated. Pandas does not run Excel's calculation engine. It reads whatever value was stored with the file.

Losing leading zeros in codes. Postal codes, product IDs and phone numbers read as integers drop their leading zeros. Force those columns to strings with dtype.

Merging cells and expecting tidy data. Merged cells appear as a value in the top-left cell and blanks elsewhere, which breaks grouping. Fill them down with df.ffill() or clean them in Excel first.

Tips

  • Use pd.ExcelFile() once and then call .parse(sheet_name) for each sheet. This avoids reopening the file repeatedly when you loop through many tabs.
  • Read a small sample first with nrows=100 while you figure out header offsets and column names, then remove the limit for the full run.
  • Keep column names clean by lowercasing and replacing spaces early: df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_").
  • If you only need cell values and no DataFrame, openpyxl's load_workbook lets you walk cells directly, which is useful for small, irregular layouts.
  • Never commit sensitive workbooks or their exported copies to a shared repository; strip personal data before sharing results.

Troubleshooting

FileNotFoundError. The path is wrong or the filename has a typo or hidden extension. Print the full path, then check the file exists at that exact location. Watch for duplicate extensions such as report.xlsx.xlsx.

ModuleNotFoundError for pandas or openpyxl. The package is installed in a different Python interpreter than the one running your script. Check with python -m pip list and install using python -m pip install pandas openpyxl to target the same interpreter.

ValueError: Excel file format cannot be determined. The file is not a real Excel file, perhaps an HTML table or CSV renamed to .xlsx. Open it in Excel to confirm, then use read_csv if it is actually delimited text.

UnicodeDecodeError or odd characters. This usually points to an encoding problem in a CSV rather than a workbook. For workbooks, check the original file for corrupt content by opening it in Excel and saving a fresh copy.

Wrong columns or misaligned data. The header row is not where pandas thinks it is. Experiment with header=None to see the raw table, then set header and skiprows accordingly.

Blank values where formulas should be. The cached values were never saved. Re-save the file in Excel, or read with openpyxl and data_only=True to inspect what is stored.

If that did not work, isolate the problem: read a freshly created workbook with three rows in a new script. If that succeeds, the issue is your original file's structure or path, not your Python setup.

Frequently Asked Questions

Can I read an old .xls file?

Yes. Install xlrd with pip and pandas will use it automatically for the legacy format. Very old or password-protected files may still fail.

Do I need Excel installed?

No. pandas and openpyxl read the file format directly, so this works on servers and in containers without Microsoft Office.

How do I read only part of a sheet?

Use nrows to limit rows, usecols to limit columns, and skiprows to skip the top. For arbitrary ranges, use skiprows and nrows together.

Why are my dates coming in as numbers?

The cells are probably stored as serial numbers rather than date-formatted values. Convert them with pd.to_datetime(df["Date"], origin="1899-12-30", unit="D"), adjusting the origin for your country's date system if needed.

Can I read a password-protected workbook?

Pandas does not prompt for passwords. You need to remove the protection in Excel first, or use a library that supports decryption for the specific format.

Is there a size limit?

No hard limit, but very large sheets consume memory fast. Read selected columns, filter rows, or consider converting the workbook to CSV for huge datasets.