Skip to content
Advertisement

Converting Excel to PDF with pywin32 [Error]

I try to export one of my xlsx files as PDF with pywin32:

# Import Module
from win32com import client
  
# Open Microsoft Excel
excel = client.Dispatch("Excel.Application")
  
# Read Excel File
sheets = excel.Workbooks.Open('C:/Users/xxx/MyExcel.xlsx')
work_sheets = sheets.Worksheets[4]
  
# Convert into PDF File
work_sheets.ExportAsFixedFormat(0,'C:/Users/xxx/MyPDF.pdf')

Unfortunately I get this com_error:

com_error: (-2147352567, 'Ausnahmefehler aufgetreten.', (0, 'Microsoft Excel', 'Das Dokument wurde nicht gespeichert. Das Dokument ist möglicherweise geöffnet, oder beim Speichern ist ein Fehler aufgetreten.', 'xlmain11.chm', 0, -2146827284), None)

In the end I want to do use this conversion on 30 xlsx files at once. I know how to write the loop for this but can not fix the above mentioned error.

Advertisement

Answer

When using Python paths on Windows, you need to use \ not /. So convert all your paths to use the double backslash instead of the forward slash:

sheets = excel.Workbooks.Open('C:\Users\xxx\MyExcel.xlsx')
...
work_sheets.ExportAsFixedFormat(0,'C:\Users\xxx\MyPDF.pdf')

Your ExportAsFixedFormat function call looks fine so I don’t see any other problem.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement