Search code examples
pythonexcelpywin32

pywin32 excel find how many sheets are in a workbook and index by number?


How do I find the number of sheets in a workbook in pywin32?

Also, is there ANY documentation on how to use pywin32 with excel? I can't seem to even find code examples or anything.


Solution

  • from win32com.client import Dispatch
    
    xl= Dispatch("Excel.Application")
    xl.Visible = True # otherwise excel is hidden
    
    # newest excel does not accept forward slash in path
    wb = xl.Workbooks.Open(r'U:\Example.xls')
    print "count of sheets:", wb.Sheets.Count
    for sh in wb.Sheets:
        print sh.Name
    wb.Close()
    xl.Quit()
    

    Result:

    count of sheets: 3
    Sheet1
    Sheet2
    Sheet3
    

    Your best documentation is found provided with Excel. Generally, I record a macro, look at the generated code, learn from the help file, and write what I need in Python.