Search code examples
pythonopenpyxlpython-3.7

How do you delete the last five rows in any worksheet (that could have any number of rows) with openpyxl?


So I can delete the last row if I specify it with this of course:

ws2.delete_rows(42)

But how might I delete the last five rows for example in any given worksheet if there could be any number of rows? Should I determine the max_row and then somehow loop a delete five times? Or is there another way?

I can run this five times to delete the last five rows but is there a way to do this without repeating the command?

mr = ws2.max_row
ws2.delete_rows(mr)

Solution

  • The methods delete_rows and delete_columns take an index and an optional number of items. So ws.delete_rows(ws.max_row-5, 5) should do what you want.