Search code examples
pythonexcelpywin32

How do I assign an already running process (i.e Excel) to a Python Object (PyWin32) to close it


So what I'm trying to do is:

  1. Open an Excel Workbook and input some values in cells
  2. Read the Excel file using Pandas, which coverts it to a DataFrame
  3. Carry out some operations on the DataFrame
  4. Close the Workbook (I would like to automate this step, Pandas cannot write output when Excel file is still opened)
  5. Output the results in another worksheet but same workbook
  6. Reopen the Excel Workbook to check the results

Specifically steps 4 is where I have some problems, where I have to close Excel or I will get an error (PermissionError: [Errno 13]). I know how you can use PyWin32 to open an Excel Application and do whatever but is there a way to assign the already opened Excel Workbook (opened previously from File Explorer) to a PyWin32 object?


Solution

  • Sorry, think I found a solution to what I wanted but well, I think I might have badly described my problem here in the first place. Basically, I just wanted a code to close an already opened Excel Application (maybe should have said this instead of Workbook) and write some results into it then reopen it.

    import os, sys
    import tempfile
    import win32com.client
    
    from pathlib import Path
    filename = Path.cwd() / "ExcelFile.xlsx"
    
    # Obtains the opened Excel instance
    wb1 = win32com.client.GetObject(str(filename))
    
    # Closes Excel
    wb1.Application.Quit()
    
    # Do whatever here like writing output in that Excel Workbook
    
    # Reopen that Excel file
    os.startfile(filename)
    

    Found this to be useful. Once again, sorry for the misleading description.