How to read an Excel file in Python


Introduction

In this tutorial, we will learn how to read the data from an Excel file and use the data in Python. At the end of this tutorial, you will learn how to open an Microsoft Excel file, read data from a particular column into Python.


Example

Let us assume, that the Excel file looks something like this as shown in the figure. You want  read the names/ages of all the students. Let us develop the code to read the data from Column A and Column B in to 2 variables Name and Age.

Data1
Steps

Step 1 : The first step is to import the xlrd library. We use xlrd package to read the data from Excel spreadsheets.  If xlrd library is not installed, you can download from here.

Step 2 : In this step, we will open an Excel file “Data.xlsx” in the current directory.

 

Step 3 : In the current example, we know that the data is saved in Column A and Column B. However, if we have to read multiple rows and columns and donot exactly how many rows and columns, we need to first obtain the number of rows and columns

 

Step 4 : The last step is to parse through each row and each column and read the data in the current cell.

 

 

Download

The complete Python source can be downloaded from here. Please note, that the code is tested using Python 2.7 . If you are using Python 3.3, you might have to do some minor changes in the code.

I hope, you find this article very useful. If you have any doubts or have any comments concerning this tutorial, Please leave a comment or contact me. I would be glad to help.

 

Kiran Chandrashekhar

Hey, Thanks for dropping by. My name is Kiran Chandrashekhar. I am a full-time software freelancer. I love Maths and Mathematical Shortcuts. Numbers fascinate me. I will be posting articles on Mathematical Shortcuts, Software Tips, Programming Tips in this website. I love teaching students preparing for various competitive examinations. Read my complete story.

Leave a Reply

Your email address will not be published. Required fields are marked *

Protected by WP Anti Spam