title: Python Win32Com & Excel.Application Failing to Save on Scheduler
body: <p>I am having an issue with using <code>win32com</code> and Task Scheduler. <strong>An Excel File save operation is not taking place despite other aspects of the script performing successfully</strong>. This is being run on an automation machine; there is no active login session. See facts below. </p>
  
  <p>I am new to Win32COM so I may not understand when and how it can be used in Python.</p>
  
  <h1>Background</h1>
  
  <p>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 <code>csv</code> to output data, but I learned about <code>win32com</code> to create xlsx files using Excel VBA commands.</p>
  
  <p>I extended my existing chronjob with code to wrap around existing database operations that use <code>pymysql</code>:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>The script goes through a number of database operations which take several minutes. Some export to a .csv with <code>csv</code>, and some create a new sheet and export the acquired data with this code:</p>
  
  <pre><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"
  </code></pre>
  
  <p>The program ends with this:</p>
  
  <pre><code>if wb.Sheets.Count &gt; 1:
      basesht.Delete()
      wb.SaveAs(consolidated) #consolidated = save path
  excel.Application.Quit()
  </code></pre>
  
  <h1>Facts</h1>
  
  <ol>
  <li>The task in Task Scheduler is setup properly with an administrator account. This is confirmed by other files in the script being created.</li>
  <li>Running the script while logged into the automation machine will properly create the Excel file and save. </li>
  <li>Task Scheduler reports 0x1 error upon completion.</li>
  </ol>
  
  <p>I dived headfirst into Win32Com so I expect I am missing something. Why won't this script save a file?</p>