Saturday, 2 November 2013

How to read excel file in python



For reading excel file, you have to download openpyxl library. By the help of openpyxl library we can read easily cell by cell in xls, xlsx file.

First Download Openpyxl library from here or Download

From below code you can read excel file cell by cell.

Here I have hardcoded file location for xlsx file, so you can use this code as usual.

from openpyxl import load_workbook
match=’D:\\project\test.xlsx’

try:

    wb = load_workbook(filename = match, use_iterators = True)

    totalsheet= wb.get_sheet_names()

    for tot in totalsheet:

        ws = wb.get_sheet_by_name(name = tot)

        for row in ws.iter_rows(): # it brings a new method: iter_rows()

           for cell in row:

              if cell.internal_value != None:

                  print cell.internal_value

except:

     print "Oops!  That was no valid number.  Try again..."

No comments:

Post a Comment