Read your Excel file with XLRD module

Hey Guys, in this section we will be dealing with some of the Advanced topics of Python. But prior to this i assume that you people have sound knowledge of Python. If not, then i would suggest you to go through the Beginner’s Section of our tutorial for better understanding.

XLRD Module

So lets get started with XLRD module. XLRD module provides a library for Developers to extract data from MS Excel spreadsheet files.This is not an end-user tool. It allow us to extract datas from any spreadsheet files with extensions .xls and .xlsx on any platform. This module provides us a range of operations to perform on the excel sheet, it include functions to specify the working cell value, selecting a particular sheet to work on, opening our Spreadsheet file and so on

Versions of python supported : 2.6, 2.7, 3.2+

Download Links :

http://pypi.python.org/pypi/xlrd

http://www.lexicon.net/sjmachin/xlrd.htm

Lets demonstrate the working of XLRD with this small example :

 

  import xlrd
    def main():
          book = xlrd.open_workbook("myfile.xls")
          print "The number of worksheets is", book.nsheets
          print "Worksheet name(s):", book.sheet_names()
          sh = book.sheet_by_index(0)
          print sh.name, sh.nrows, sh.ncols
     if __name__ == “ __main__”
          main()

For the above example, in the first line i have imported the XLRD module without it we cannot extract that data’s from the excel. In line number 3 i am opening the Workbook which is nothing but my Spreadsheet file (remember that file extension which is accepted by XLRD is either .xls or .xlrd ), so in the next line i am simply printing the number of sheets in the Workbook using the handle “book”. In line 4, i am displaying the worksheet name using the function “sheet_names()”.

Now you need to actually start working on your excel sheet for which you have to choose the index to work on in this context the index means the sheets in the file ( Note that the reference to the index starts from 0 not from 1 ), so to accomplish this task xlrd provides you the function “sheet_by_index(index)” and using its variable you can get the name of the sheet, number of rows,column and so on.

So here is our little effort to make you understand the basic concept of XLRD module in lame terms.

If you have any queries or question, please feel free to comment below. We are always here to help you.