×

Python Read Excel file

Python Read Excel file

Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the data. It is widely used in many different software fields.

An excel spreadsheet document is saved in the file with .xlsx extension. The first row of the spreadsheet commonly reserved for the header, while the first column identifies the sampling unit.

A box at a specific column and row is called a cell, and each cell can include a number or text value. The grid of cells with data forms a sheet.

Read from the Excel file

Python provides facilities to read, write, and modify the excel file. The xlrd module is used to work with the excel file. Python does not come with the xlrd module. First, we need to install this module by using following command:

pip install xlrd

Creating a Workbook:

A workbook holds all the data in the excel file. Let’s consider the following input (excel) file.

Python Read from the Excel file

Consider the following code:

import xlrd
# Give the location of the file
loc = ("location of file")
 # To open a Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0) 
 #for row 0 and column 0
sheet.cell_value(0, 0) 

In the above example, first, we imported the xlrd module and declared the loc variable, which holds the location of the file. Then we opened the working workbook from the excel file.

  • Extract the number of columns and rows
import xlrd
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0,0)
print("The number of column:",sheet.ncols)
print("The number of rows:",sheet.nrows)

Output:

The number of column: 3
The number of rows: 7
  • Extracting all column name
import xlrd
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
for i in range(sheet.ncols):
    print(sheet.cell_value(0, i))

Output:

Roll No.
Name
Year 
  • Extracting a particular row value
import xlrd
# loc = ("location of file")
loc = ("location of file")
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# For row 0 and column 0
sheet.cell_value(0, 0)
print(sheet.row_values(1)) #It will return an list containing the row value
print(sheet.row_values(2)) #It will return an list containing the row value

Output:

[90017.0, 'Himanshu Dubey', 1.0]
[90018.0, 'Sachin Tiwari', 1.0] 

Reading from the Pandas

Pandas is an open-source Python library which is built on the top of the NumPy library. First, we need to import the pandas module. It supports both xls and xlsx extensions from the URL. Consider the following example:

import pandas as pd
#Using read_excel function to read file
df = pd.read_excel('location of file')
print(df) 

Output:

 Roll No. Name Year
 0 90017 Himanshu Dubey 1
 1 90018 Sachin Tiwari  1
 2 90019 Krishna Shukla 1
 3 80014 Prince Sharma  2
 4 80015 Anubhav Panday 2
 5 80013 Aradhya        3  
  • Exacting rows name
import pandas as pd
#Using read_excel function to read file
df = pd.read_excel('location of file')
print(df.columns) 

Output

(['Roll No.', 'Name', 'Year'], dtype='object')

Reading from the openpyxl

Python provides openpyxl which can perform multiple operations on the excel files such as reading, writing, and arithmetic operations. We need to install openpyxl using pip from the command line.

import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet_title = sheet.title
print("My sheet title: " + sheet_title)

Output:

My sheet title: Sheet

Related Topics

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.