Can';t使用Python';是win32com API吗?

Can';t使用Python';是win32com API吗?,python,excel,pdf,win32com,Python,Excel,Pdf,Win32com,尝试从Excel自动创建PDF。我可以毫无问题地保存为Excel文件,但不能保存为PDF def run_excel(fname, col, rows): save_dir = os.path.join(os.path.dirname(fname), 'saved') save_file = os.path.join(save_dir, os.path.basename(fname)) save_pdf = os.path.join(os.path.splitext(sa

尝试从Excel自动创建PDF。我可以毫无问题地保存为Excel文件,但不能保存为PDF

def run_excel(fname, col, rows):
    save_dir = os.path.join(os.path.dirname(fname), 'saved')
    save_file = os.path.join(save_dir, os.path.basename(fname))
    save_pdf = os.path.join(os.path.splitext(save_file)[0], '.pdf')
    excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
    book = excel.Workbooks.Open(Filename=fname)
    del_column(excel, book, col)
    del_row(excel, book, rows)
    # this works fine..    
    # book.SaveAs(save_file)
    book.SaveAs(save_pdf, FileFormat=c.xlTypePDF) # this does not.
    sheet = None
    book = None
    excel.Quit()
    excel = None
我的回溯:

Traceback (most recent call last):
  File "C:/scripts/excel/col_delete.py", line 33, in <module>
    run_excel(f, 'D', ('2', '4'))
  File "C:/scripts/excel/col_delete.py", line 24, in run_excel
    book.SaveAs(save_pdf, FileFormat=c.xlTypePDF)
  File "C:\Python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7\_Workbook.py", line 259, in SaveAs
    , Local)
com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'SaveAs method of Workbook class failed', u'xlmain11.chm', 0, -2146827284), None)
回溯(最近一次呼叫最后一次):
文件“C:/scripts/excel/col_delete.py”,第33行,在
运行excel(f,'D',('2','4'))
文件“C:/scripts/excel/col_delete.py”,第24行,在run_excel中
book.SaveAs(save_pdf,FileFormat=c.xlTypePDF)
文件“C:\Python27\lib\site packages\win32com\gen_py\00020813-0000-0000-C000-0000000000 46x0x1x7\\ u Workbook.py”,第259行,保存为
,本地)
com_错误:(-2147352567,‘发生异常’,(0,u'Microsoft Excel',u'SaveAs工作簿类方法失败',u'xlmain11.chm',0,-2146827284),无)

Excel似乎没有将SaveAs用于PDF格式。相反,我们需要使用ExportAsFixedFormat

这是我的工作代码,供其他可能需要它的人使用

def to_pdf(fname):
    save_pdf = os.path.splitext(fname)[0] + '.pdf'
    excel = win32com.client.gencache.EnsureDispatch("Excel.Application")
    book = excel.Workbooks.Open(Filename=fname)
    book.ExportAsFixedFormat(c.xlTypePDF, save_pdf)
    sheet = None
    book = None
    excel.Quit()
    excel = None