我正在尝试使用 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,效果很好。
关于如何解决文件格式错误的问题有什么想法吗?
最佳答案
找到了一个解决方案 - 这似乎有效:
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 (尽管某些参数的值必须稍作修改)。
关于python - 在Python中使用comtypes将Excel文档转换为pdf时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445033/