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
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
iter_rows(min_row=None, max_row=None, min_col=None, max_col=None, values_only=False)
Returns a generatorfor 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()
iter_cols(min_col=None, max_col=None, min_row=None, max_row=None, values_only=False)
This is not available in read only mode. wb = load_workbook(filename='D:\student.xlsx', read_only=False)
Getting Name column data for 6 records
for data in ws.iter_cols(min_row=2,min_col=2,max_row=6,max_col=2,values_only=True):
print(data)
Output
('John Deo', 'Max Ruin', 'Arnold', 'Krish Star', 'John Mike')
To include the column header ( Name ) we will remove the option min_row=2
for data in ws.iter_cols(min_col=2,max_row=6,max_col=2,values_only=True):
print(data)
Output
('name', 'John Deo', 'Max Ruin', 'Arnold', 'Krish Star', 'John Mike')
print(ws.max_column) # Max column count, output is 5
print(ws.max_row) # Max row count, output is 36
print(ws.cell(ws.max_row, 1).value)
To generate a sequence of unique numbers for List, use enumerate().
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.