Error when converting Excel document to pdf using comtypes in Python

后端 未结 2 474
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 17:03

I am trying to convert an Excel spreadsheet to PDF using Python and the comtypes package using this code:

import os
import comtypes.client

FORMAT_PDF = 17
S         


        
2条回答
  •  梦毁少年i
    2021-01-15 17:41

    You need to describe ExportAsFixedFormat(0,outputfile) to save workbook in pdf format. The solution from http://thequickblog.com/convert-an-excel-filexlsx-to-pdf-python/ works for me.

    from win32com import client
    import win32api
    input_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample.xlsx'
    #give your file name with valid path 
    output_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample_output.pdf'
    #give valid output file name and path
    app = client.DispatchEx("Excel.Application")
    app.Interactive = False
    app.Visible = False
    Workbook = app.Workbooks.Open(input_file)
    try:
        Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
    except Exception as e:
        print("Failed to convert in PDF format.Please confirm environment meets all the requirements  and try again")
        print(str(e))
    finally:
        Workbook.Close()
        app.Exit()
    

提交回复
热议问题