Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the last row in a column using openpyxl normal workbook?

I'm using openpyxl to put data validation to all rows that have "Default" in them. But to do that, I need to know how many rows there are.

I know there is a way to do that if I were using Iterable workbook mode, but I also add a new sheet to the workbook and in the iterable mode that is not possible.

like image 754
human Avatar asked Nov 05 '15 10:11

human


People also ask

How do I find the last cell in a workbook?

To find the last row, column, or the cell you can use the range's “End” property. The end property allows you to navigate to the end of the data range (to the last cell that is not empty).

How do I select the last row in Excel with data?

Tip: You can also click the first column heading, and then press CTRL+SHIFT+END. To select all rows below the last row that contains data, click the first row heading, hold down CTRL, and then click the row headings of the rows that you want to select.

How do I get Max rows in Openpyxl?

To find the max row and column number from your Excel sheet in Python, use sheet. max_row and sheet. max_column attributes in Openpyxl. Note - If you update a cell with a value, the sheet.


2 Answers

ws.max_row will give you the number of rows in a worksheet.

Since version openpyxl 2.4 you can also access individual rows and columns and use their length to answer the question.

len(ws['A'])

Though it's worth noting that for data validation for a single column Excel uses 1:1048576.

like image 188
Charlie Clark Avatar answered Sep 21 '22 03:09

Charlie Clark


This works for me well. It gives number of non empty rows in each column, assuming there are no empty rows in between.

from openpyxl import load_workbook as lw from openpyxl.utils import get_column_letter  wb = lw(your_xlsx_file) ws = wb[sheet_name]  for col in range(1, ws.max_column + 1):     col_letter = get_column_letter(col)     max_col_row = len([cell for cell in ws[col_letter] if cell.value])     print("Column: {}, Row numbers: {}".format(col_letter, max_col_row) 
like image 31
DannyG Avatar answered Sep 22 '22 03:09

DannyG