如何删除python python中的excel行

问题描述:

亲爱的,全部。如何删除python python中的excel行

如果单元格(i,5)没有值,我想在python 3.6中用python pywin32删除excel中的行。

这是我的代码。

def qms(self): 
    fname = QtWidgets.QFileDialog.getOpenFileName(self) 

    if fname[0]: 
     self.Filename.setText(fname[0]) 
     excel = win32com.client.Dispatch("Excel.Application") 
     excel.Visible = True 
     f = excel.Workbooks.Open(fname[0]) 
     fs = f.ActiveSheet 
     lastrow = fs.UsedRange.Rows.Count 

     for i in range(3, lastrow): 
      if not fs.Cells(i,5).Value : 
       fs.getCells().deleteRows(i-1,1,True) 

     excel.Workbooks.save() 
     excel.Quit() 

我认为fs.getCells()。deleteRow(i-1,1,True)有问题。 我无法理解。你可以帮帮我吗?

for i in range(lastrow, 2, -1): 
    if fs.Cells(i,5).Value != "" 
     fs.Rows(i).EntireRow.Delete() 

或者你也许可以删除所有一次:

fs.UsedRange.Offset(2).Columns(5).SpecialCells(4).EntireRow.Delete() 

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-specialcells-method-excel

+0

谢谢你帮助我。 但我不明白fs.UsedRange.Offset(2).Columns(5).SpecialCells(4).EntireRow.Delete() –

def qms(self): 
    fname = QtWidgets.QFileDialog.getOpenFileName(self) 

    if fname[0]: 
     self.Filename.setText(fname[0]) 
     excel = win32com.client.Dispatch("Excel.Application") 
     excel.Visible = True 
     f = excel.Workbooks.Open(fname[0]) 
     fs = f.ActiveSheet 
     lastrow = fs.UsedRange.Rows.Count 

     for i in range(lastrow, 2, -1): 
      if fs.Cells(i,5).Value == None or fs.Cells(i,5).Value == "": 
       fs.Rows(i).EntireRow.Delete()