Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Cells
Summary

Instruction

Very good!

Let's discuss finding the boundaries of a given worksheet. The authors of openpyxl have provided us with properties to handle a number of needs. Assuming that we've already loaded an xlsx file and selected a given worksheet, we can use the max_row and max_column properties to find the worksheet's boundary:

sweets_max_row = sweets_ws.max_row
sweets_max_column = sweets_ws.max_column

Both max_row and max_column return an integer that indicates the last populated row/column in a worksheet. If your worksheet has 20 rows of data (counting from A1), max_row property will return a 20. However, if you have 15 rows of data (again counting from A1), then five empty rows, and then three rows of data, it will show 23.

Exercise

Find the worksheet with the greatest number of rows in the january_diet.xlsx file. Assign the name of the worksheet with the greatest number of rows to the longest_ws variable and print it, together with the number of rows it contains, e.g.:

workout 35

Stuck? Here's a hint!

First you'll need to initialize two variables, one for holding the number of rows and one for holding the name of the worksheet with the greatest number of rows:

row_count = 0
longest_ws = ""

Then, we need to iterate over all worksheets in the workbook and check their row count using the max_row property. If the row_count is smaller than the current worksheet max_row, update both row_count and longest_ws with appropriate values. Remember that:

  • These two variables have to be initialized before the loop.
  • The sheetnames property may come in handy, but it returns a list of worksheet names, not the worksheets themselves.