2

尝试从 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)
4

1 回答 1

2

看起来 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
于 2013-09-18T13:03:03.720 回答