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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import xlrd, pymsgbox workbook = xlrd.open_workbook('D:/SampleexcelFile.xlsx') sheet = workbook.sheet_by_name('practice') rowcount = sheet.nrows colcount = sheet.ncols print('Total number of rows: ' + str(rowcount)) print('Total number of columns: ' + str(colcount)) result_data =[] 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) pymsgbox.alert(result_data, 'Result') |
Decoding of the code:
- 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.
- 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
- sheet = workbook.sheet_by_name(‘practice’) -> In this step, data will be read from excel sheet named ‘practice’ which is present inside opened excel.
- rowcount = sheet.nrows, colcount = sheet.ncols -> This step will return total count of rows and columns present inside the excel sheet.
- print(rowcount), print(colcount) -> here we are printing number of rows and columns.
- result_data =[], row_data = [] -> Declared two empty list.
- 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. - 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’.