Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Openpyxl sheet.dimensions

I have a spreadsheet with data and want to know the first and last cell of the range that contains data. I use Python with Openpyxl. The sheet.dimensions property returns the top-left and bottom-right cell of the area of non-empty cells.
How can I put the outcome of sheet.dimensions in 2 variables. Example: result of sheet.dimensions is A2:C20.
I need one variable containing the first cell of the range (in this case A2) and the other variable containing the last cell of the range (in this case C20).
I expected something like sheet.dimensions.first and .last but so far I can not find the answer.

the spreadsheet

The program to its basics is as follows:

import openpyxl

book = openpyxl.load_workbook('test 1.xlsx', data_only=True)
sheet = book.active

print (sheet.dimensions)

book.save("result test 1.xlsx")

When the program is run it gives the result A2:C20.

like image 969
Marionet Avatar asked Jun 08 '26 23:06

Marionet


1 Answers

I found that openpyxl has the following attributes:

  • sheet.min_row
  • sheet.max_row
  • sheet.min_column
  • sheet.max_column

These are exactly the numbers that I need and with these I know how many iterations are needed to process the whole worksheet. Example:

import openpyxl

book = openpyxl.load_workbook('test 1.xlsx', data_only=True)
sheet = book.active

mi_row = sheet.min_row
ma_row = sheet.max_row
mi_col = sheet.min_column
ma_col = sheet.max_column

print(mi_row, mi_col, ma_row, ma_col)

for row in sheet.iter_rows(min_row=mi_row, min_col=mi_col, max_row=ma_row, max_col=ma_col):
    for cell in row:
        pop = (cell.value)
        print(pop)
like image 71
Marionet Avatar answered Jun 11 '26 16:06

Marionet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!