I am having an issue with using win32com
and Task Scheduler. An Excel File save operation is not taking place despite other aspects of the script performing successfully. This is being run on an automation machine; there is no active login session. See facts below.
I am new to Win32COM so I may not understand when and how it can be used in Python.
Background
I have a Python script that runs overnight through Task Scheduler which gathers data from an internal database and outputs it into a report. The original script used csv
to output data, but I learned about win32com
to create xlsx files using Excel VBA commands.
I extended my existing chronjob with code to wrap around existing database operations that use pymysql
:
import win32com.client as win32
try:
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Add()
basesht = wb.Sheets('Sheet1')
except:
#E-mail notification of failure.
sys.exit()
The script goes through a number of database operations which take several minutes. Some export to a .csv with csv
, and some create a new sheet and export the acquired data with this code:
#For Each Report in Report Set (DB = Object extending pymysql)
resultSet = db.qryfetchall()
headers = list(resultSet[0].keys())
r, c = 1, len(headers)
wksht.Range(wksht.Cells(r,1),wksht.Cells(r,c)).Value = headers
for row in resultSet:
r += 1
wksht.Range(wksht.Cells(r,1),wksht.Cells(r,c)).Value = [str(i) for i in list(row.values())]
wksht.Columns.AutoFit()
else:
wksht.Range("A1").Value = "No Results"
The program ends with this:
if wb.Sheets.Count > 1:
basesht.Delete()
wb.SaveAs(consolidated) #consolidated = save path
excel.Application.Quit()
Facts
- The task in Task Scheduler is setup properly with an administrator account. This is confirmed by other files in the script being created.
- Running the script while logged into the automation machine will properly create the Excel file and save.
- Task Scheduler reports 0x1 error upon completion.
I dived headfirst into Win32Com so I expect I am missing something. Why won't this script save a file?