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.
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).
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.
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.
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With