Home > Microsoft Excel > Read excel sheet using Python

Read excel sheet using Python

This post was most recently updated on August 5th, 2024

  • Below code will show how to read excel and display data in python. 
  • For reading data in excel we will be using ‘xlrd’ library. This library can be downloaded from this link

Decoding of the code:

  1. import xlrd, pymsgbox -> We have imported two libraries ‘xlrd’ and ‘pymsgbox’. ‘xlrd’ library is used for excel operations like reading from and writing data to excel. ‘pymsgbox’ is used here for showing popup/alert message.
  2. workbook = xlrd.open_workbook(‘D:/SampleexcelFile.xlsx’) -> Using this line we will open excel file from mentioned location. Sample Excel file can be found here: SampleexcelFile
  3. sheet = workbook.sheet_by_name(‘practice’) -> In this step, data will be read from excel sheet named ‘practice’ which is present inside opened excel.
  4. rowcount = sheet.nrows, colcount = sheet.ncols -> This step will return total count of rows and columns present inside the excel sheet.
  5. print(rowcount), print(colcount) -> here we are printing number of rows and columns.
  6. result_data =[], row_data = [] -> Declared two empty list.
  7. for row in range(1, rowcount):
    row_data = []
    for column in range(0, colcount):
    data = sheet.cell_value(row, column)
    row_data.append(data)
    print(row_data)
    result_data.append(row_data)
    Inner for loop will iterate through different columns on same row to get the cell value. Each cell value is added to the ‘list’ called ‘row_data’
    Outer for loop will iterate on number of rows mentioned inside a variable called ‘rowcount’.
    Values in ‘row_data’ are appended to ‘result_data’ list.
  8. pymsgbox.alert(result_data, ‘Result’) -> In this final step, all cell values present in excel sheet are shown to user on alert message box with title naming ‘Result’.
This Article is TAGGED in . BOOKMARK THE permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">