使用Python中的comtypes将Excel文档转换为pdf时出错

时间:2017-09-27 10:04:21

标签: python excel comtypes

我正在尝试使用Python和使用此代码的comtypes包将Excel电子表格转换为PDF:

import os
import comtypes.client

FORMAT_PDF = 17
SOURCE_DIR = 'C:/Users/IEUser/Documents/jscript/test/resources/root3'
TARGET_DIR = 'C:/Users/IEUser/Documents/jscript'

app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False

infile = os.path.join(os.path.abspath(SOURCE_DIR), 'spreadsheet1.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'spreadsheet1.pdf')

doc = app.Workbooks.Open(infile)
doc.SaveAs(outfile, FileFormat=FORMAT_PDF)
doc.Close()

app.Quit()

上面的这个脚本运行正常并且创建了pdf文件,但是当我尝试打开它时,我收到错误“文件无法打开 - 文件格式有问题”(但在关闭此错误对话框后实际上可以预览pdf文件)。我尝试过类似的脚本将Word文档转换为pdf文件,这很好用。

有关如何使用文件格式错误解决此问题的任何想法?

2 个答案:

答案 0 :(得分:1)

找到解决方案 - 这似乎有效:

import os
import comtypes.client

SOURCE_DIR = 'C:/Users/IEUser/Documents/jscript/test/resources/root3'
TARGET_DIR = 'C:/Users/IEUser/Documents/jscript'

app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False

infile = os.path.join(os.path.abspath(SOURCE_DIR), 'spreadsheet1.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'spreadsheet1.pdf')

doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()

app.Quit()

此链接也可能有助于作为ExportAsFixedFormat函数的参数的灵感:Document.ExportAsFixedFormat Method(尽管某些参数值必须稍微修改一下)。

答案 1 :(得分:0)

您需要描述ExportAsFixedFormat(0,outputfile)才能将工作簿保存为pdf格式。 http://thequickblog.com/convert-an-excel-filexlsx-to-pdf-python/的解决方案对我有用。

from win32com import client
import win32api
input_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample.xlsx'
#give your file name with valid path 
output_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample_output.pdf'
#give valid output file name and path
app = client.DispatchEx("Excel.Application")
app.Interactive = False
app.Visible = False
Workbook = app.Workbooks.Open(input_file)
try:
    Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
except Exception as e:
    print("Failed to convert in PDF format.Please confirm environment meets all the requirements  and try again")
    print(str(e))
finally:
    Workbook.Close()
    app.Exit()