【问题标题】:Can't Save Excel 2010 files as PDF using Python's win32com API?无法使用 Python 的 win32com API 将 Excel 2010 文件另存为 PDF?
【发布时间】:2013-09-22 08:05:22
【问题描述】:

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

【问题讨论】:

    标签: python excel pdf win32com


    【解决方案1】:

    看起来 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2020-01-22
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多