使用Python中的类型将Excel文档转换为pdf时出错 [英] Error when converting Excel document to pdf using comtypes in Python
问题描述
我正在尝试使用Python和使用此代码的comtypes包将Excel电子表格转换为PDF:
I am trying to convert an Excel spreadsheet to PDF using Python and the comtypes package using this code:
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,并且效果很好.
This script above runs fine and the pdf file is created, but when I try to open it I get the error "The file cannot be opened - there is a problem with the file format" (but after closing this error dialog it is actually possible to preview the pdf file). I have tried a similar script to convert Word documents to pdfs and this worked just fine.
关于如何解决文件格式错误的任何想法?
Any ideas on how I can resolve this problem with the file format error?
推荐答案
找到了解决方案-似乎可行:
Found a solution - this seems to be working:
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
函数的参数的启发也可能会有所帮助:
This link may also be helpful as an inspiration regarding the arguments to the ExportAsFixedFormat
function: Document.ExportAsFixedFormat Method (although some of the values of arguments have to be modified a bit).
这篇关于使用Python中的类型将Excel文档转换为pdf时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!