8

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()
2
  • 1
    Is this the answer you're looking for? stackoverflow.com/questions/4439689/… Commented Feb 21, 2019 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? Commented Feb 22, 2019 at 11:16

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works for me if there is already an Excel Application open, not sure if that's the same case for everyone else
This doesn't work for me with or without the application already open.
4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.