×

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

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

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.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Python e-book free download

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. There are many sources to learn python. In this...

3 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.