Search code examples
pythonexcelpywin32win32com

Printing Excel sheets with COM interface


I've programatically made a bunch of Excel sheets with xlwt in python. It's all gone fine, but now I need to convert them all to pdf. I've been trying to do this with pywin32 and the com interface. I can get somewhat close by going like this:

import win32com.client
o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
wb = o.Workbooks.Open('foo.xls')
ws = wb.Worksheets[1]
ws.printout()

But unfortunately when I do this it pops up the adobe printer screen asking me for the path I want to save the pdf to, and if I have to enter that in or click ok for every page it defeats the purpose of doing it programatically. Is there any way I can enter this path in the python code rather than manually? Is there a better way of converting each of these sheets in each of these workbooks to pdf? Thanks a lot, Alex


Solution

  • Instead of using the PrintOut method, use ExportAsFixedFormat. You can specify the pdf format and supply a file name. Try this:

    ws.ExportAsFixedFormat(0, 'c:\users\alex\foo.pdf')