How to read an Excel file in Python?

Published on Aug. 22, 2023, 12:19 p.m.

To read an Excel file in Python, you can use the pandas library. Here is an example:

import pandas as pd

# Read the Excel file into a pandas DataFrame
df = pd.read_excel('example.xlsx')

# Print the DataFrame
print(df)

In this example, we first imported the pandas library. We then used the read_excel() function to read an Excel file named ‘example.xlsx’ into a pandas DataFrame. The resulting DataFrame contains all the data from the Excel file.

You can specify additional options when reading the Excel file, such as the sheet name using the sheet_name parameter. For example:

# Read the second sheet of the Excel file into a pandas DataFrame
df = pd.read_excel('example.xlsx', sheet_name='Sheet2')

This will read the second sheet of the Excel file ‘example.xlsx’ into a pandas DataFrame.

Note that you need to have pandas and any required dependencies installed to use this functionality. You can install pandas using pip:

pip install pandas

Tags: