Skip to main content
 首页 » 编程设计

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

2024年10月01日6myhome

我正在尝试使用 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 (虽然参数的一些值必须修改一下)。