Openpyxl library to read Excel file from cell or rows columns by using max min rows and columns
Opening Excel file
from openpyxl import load_workbook
wb = load_workbook(filename='D:\student.xlsx', read_only=True) # change path
ws = wb['student'] # connecting to sheet
wb.close()# Close the workbook after reading
Reading a cell value
Here cell with row=2 and column=3 ( 1 - based index ) value is printed.
from openpyxl import load_workbook
wb = load_workbook(filename='D:\student.xlsx', read_only=True)
ws = wb['student'] # connecting to sheet
print(ws.cell(2,3).value)# One particular cell value
wb.close()# Close the workbook after reading
Returns a generator
If range is not given then it starts from A1
We will get ID ( first column ) and Name( second column ) values of five records including header row
for data in ws.iter_rows(max_col=5,max_row=5,values_only=True):
print(data[0],data[1]) # Show column 1,2 - id, name
Show id, name , class,mark and gender columns ( all columns ) upto 5th row.
for data in ws.iter_rows(max_col=5,max_row=5,values_only=True):
for d in range(len(data)):
print(data[d],end=' ') # print all data of a row
print('') # adding line break
Output
id name class mark gender
1 John Deo Four 75 female
2 Max Ruin Three 85 male
3 Arnold Three 55 male
4 Krish Star Four 60 female
Remove the header and only show up to 5th row
for data in ws.iter_rows(min_row=2,max_col=5,max_row=6,values_only=True):
for d in range(len(data)):
print(data[d],end=' ') # print all data of a row
print('') # adding line break at end of each row
Output
1 John Deo Four 75 female
2 Max Ruin Three 85 male
3 Arnold Three 55 male
4 Krish Star Four 60 female
5 John Mike Four 60 female
To get all the rows we can remove the max_rows=6 option in inter_rows()
print(ws.max_column) # Max column count, output is 5
print(ws.max_row) # Max row count, output is 36
Data of Last row
This can be used to generate next record id ( similar to auto incremented id column of MySQL database. )
The first column data of last row is printed here.