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()
3 Answers 3
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.
2 Comments
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.
Comments
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
.Visibleproperty. But OP says that Excel does have that property, and since I am using Excel,.Visibleshould work right?