6

I am trying to convert an excel file to PDF. Using Print chosen worksheets in excel files to pdf in python and Python - Converting XLSX to PDF, I wrote the code below.

This converts the excel to PDF without a problem but it opens the excel file. I thought the point of the .Visible = False was to prevent this? I would like the excel object to stay hidden because I am doing this to over 100 files and I do not want excel opening up 100 times.

import win32com.client
import os
import re

nm = 'Sample.xlsx'

excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
wb = excel.Workbooks.Open('{0}\\{1}'.format(os.getcwd(), nm))
wb.WorkSheets('Report').Select()
nm_pdf = re.sub('.xlsx', '.pdf', nm, count = 1)
wb.ActiveSheet.ExportAsFixedFormat(0, '{0}\\{1}'.format(os.getcwd(), nm_pdf))
#excel.Quit()
phil_t
  • 851
  • 2
  • 7
  • 17
  • 1
    Is this the answer you're looking for? https://stackoverflow.com/questions/4439689/how-to-hide-com-object-dispatched-from-python – Sirsmorgasboard Feb 21 '19 at 21:10
  • @Sirsmorgasboard, that is a workaround for an application that does not have the `.Visible` property. But OP says that Excel does have that property, and since I am using Excel, `.Visible` should work right? – phil_t Feb 22 '19 at 11:16

3 Answers3

4

Neither of the methods above worked for me but finally this did the job, maybe it's gonna be of some use for someone:

excel.ScreenUpdating = False
excel.DisplayAlerts = False
excel.EnableEvents = False

*set it all back to True after you finish processing the file.

Blaydice
  • 74
  • 5
  • 1
    This works for me if there is already an Excel Application open, not sure if that's the same case for everyone else – Josh Pachner Jan 12 '21 at 20:29
3

to anyone who has this problem, this is what helped me:

excel = client.Dispatch("Excel.Application")
excel.Interactive = False
excel.Visible = False

The "Interactive = False" part is what i was missing. Visible set to False by itself didn't do the trick. Also don't forge to close the workbook.

vikino
  • 109
  • 1
  • 7
0

I found that when starting the program with an Excel sheet open, it would continue to open and run as though set to Visible = True. If I started the program with no Excel file open, it would run as expected (not opening Excel).

excel = w32.Dispatch("Excel.Application")
excel.Interactive = False
excel.Visible = False
excel.DisplayAlerts = False