How to delete rows that satisfy some criteria in an excel spreadsheet?

前端 未结 2 1039
一个人的身影
一个人的身影 2021-01-04 04:10

I would like to create a \"reduced\" version of an Excel (xlsx) spreadsheet (i.e. by removing some rows according to some criterion), and I\'d like to know if this can be do

2条回答
  •  死守一世寂寞
    2021-01-04 04:29

    Internally openpyxl does not seem to have a concept of 'rows' it works with cells and keeps track of the dimensions and if you use Worksheet.rows it calculates a 2D array of cells from that. You can mutate the array, but it doesn't change the Worksheet.

    If you want to do this within the Worksheet, you need to copy the values from the old position to the new position, and set the value of the cells that are no longer needed to '' or None and call Worksheet.garbage_collect().

    If your dataset is small and of uniform nature (all strings e.g.), you might be better of copying the relevant cell (content) to a new worksheet, remove the old one and set the title of the new one to the title of the just deleted one.

    The most elegant thing to do, IMHO, would be to extend Worksheet or a subclass with a delete_rows method. I would implement such a method by changing the coordinates of its Cells in place. But this could break if openpyxl internals change.

提交回复
热议问题