I need to open an Excel sheet, refresh a pivot table, save it and close it. However, whenever I open an instance of Excel using python, no matter how hard I try, it stays open. I also want to use an already running instance, if there is one available and, if not, create one. Finally, if there was an instance running, just close the workbook and else, close Excel.
I've tried this solution to no avail. I also tried this one, but no success.
Here is the code. It does exactly what tis supposed to do, however, the Excel process remains running in the background. I can even call Application.Visible = True
and it will pop up again.
import pywintypes
import pythoncom
from win32com import client
pythoncom.CoInitialize()
try:
Application = client.GetActiveObject("Excel.Application")
Application.Visible = True
except pywintypes.com_error:
Application = client.Dispatch("Excel.Application")
Application.Visible = False
Workbook = Application.Workbooks.open('file_name.xlsx'))
Workbook.RefreshAll()
Workbook.Save()
if len(Application.Workbooks) == 1: # If there is only one workbook, close Excel
Application.Quit()
else:
Workbook.Close()
pythoncom.CoUninitialize()