In python removing rows from a excel file using xlrd, xlwt, and xlutils

后端 未结 3 856
情话喂你
情话喂你 2021-01-14 16:51

Hello everyone and thank you in advance.

I have a python script where I am opening a template excel file, adding data (while preserving the style) and saving again.

3条回答
  •  孤街浪徒
    2021-01-14 17:35

    For those of us still stuck with xlrd/xlwt/xlutils, here's a filter you could use:

    from xlutils.filter import BaseFilter
    
    class RowFilter(BaseFilter):
        rows_to_exclude: "Iterable[int]"
        _next_output_row: int
    
        def __init__(
                self,
                rows_to_exclude: "Iterable[int]",
        ):
            self.rows_to_exclude = rows_to_exclude
            self._next_output_row = -1
    
        def _should_include_row(self, rdrowx):
            return rdrowx not in self.rows_to_exclude
    
        def row(self, rdrowx, wtrowx):
            if self._should_include_row(rdrowx):
                # Proceed with writing out the row to the output file
                self._next_output_row += 1
                self.next.row(
                    rdrowx, self._next_output_row,
                )
    
        # After `row()` has been called, `cell()` is called for each cell of the row
        def cell(self, rdrowx, rdcolx, wtrowx, wtcolx):
            if self._should_include_row(rdrowx):
                self.next.cell(
                    rdrowx, rdcolx, self._next_output_row, wtcolx,
                )
    
    

    Then put it to use with e.g.:

    from xlrd import open_workbook
    from xlutils.filter import DirectoryWriter, XLRDReader
    
    xlutils.filter.process(
        XLRDReader(open_workbook("input_filename.xls", "output_filename.xls")),
        RowFilter([3, 4, 5]),
        DirectoryWriter("output_dir"),
    )
    

提交回复
热议问题