Search code examples
pythonpywin32

How to use PyWin32 to return Excel row?


What I'm looking to do is search for a value in a range, and then print the Excel row in which those values exist.

Something like:

for cell in xl.ActiveSheet.Range('A1:A30'):
    if val in cell:
        #Print rows in which that value appears

This seems like something that should be pretty simple, but I'm having some difficulty thinking of how to do it. Any help would sincerely be greatly appreciated.


Solution

  • maybe something like

    import win32com.client.dynamic
    from pythoncom import CoInitialize, CoUninitialize
    
    CoInitialize()
    xlApp = win32com.client.dynamic.Dispatch('Excel.Application')
    xlBook = xlApp.Workbooks.Open(filename)
    
    def access_range(sheet, row1, col1, row2, col2):
        "return a 2d array (i.e. tuple of tuples)"
         sht = xlBook.Worksheets(sheet)
         return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2))
    
    def get_range(sheet, row1, col1, row2, col2):
        return access_range(sheet, row1, col1, row2, col2).Value
    
    
    for column, data in enumerate(get_range(1, 1, 1, 10, 10)):
        for row, value in enumerate(data):
            if value == search_value:
                print "value found in column %s, row %s" % (chr(65+column), row+1)
    
    CoUninitialize()
    

    Note: The first sheet, column, and row is 1 (not 0)