尝试从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)
答案 0 :(得分: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