Python to delete a row in excel spreadsheet

前端 未结 6 749
走了就别回头了
走了就别回头了 2021-01-20 03:21

I have a really large excel file and i need to delete about 20,000 rows, contingent on meeting a simple condition and excel won\'t let me delete such a complex range when us

6条回答
  •  情书的邮戳
    2021-01-20 03:42

    I like using COM objects for this kind of fun:

    import win32com.client
    from win32com.client import constants
    
    f = r"h:\Python\Examples\test.xls"
    DELETE_THIS = "X"
    
    exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
    exc.Visible = 1
    exc.Workbooks.Open(Filename=f)
    
    row = 1
    while True:
        exc.Range("B%d" % row).Select()
        data = exc.ActiveCell.FormulaR1C1
        exc.Range("A%d" % row).Select()
        condition = exc.ActiveCell.FormulaR1C1
    
        if data == '':
            break
        elif condition == DELETE_THIS:
            exc.Rows("%d:%d" % (row, row)).Select()
            exc.Selection.Delete(Shift=constants.xlUp)
        else:
            row += 1
    
    # Before
    # 
    #      a
    #      b
    # X    c
    #      d
    #      e
    # X    d
    #      g
    #        
    
    # After
    #
    #      a
    #      b
    #      d
    #      e
    #      g
    

    I usually record snippets of Excel macros and glue them together with Python as I dislike Visual Basic :-D.

提交回复
热议问题