質問

Trying to automate the creation of PDFs from Excel. I can save as an Excel file without any problems, but not as a 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

My traceback:

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)
役に立ちましたか?

解決

Looks like Excel doesn't use SaveAs for PDF formats. Instead, we need to use ExportAsFixedFormat.

Here's my working code for anyone else that might need it.

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top