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

标签 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,效果很好。

关于如何解决文件格式错误的问题有什么想法吗?

最佳答案

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

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/

相关文章:

python - 获取错误 : KeyError: 'Only the Series name can be used for the key in Series dtype mappings.' when trying to do pandas Smote algorithm

python - 如何在python中将不同的excel文件合并到一个具有不同工作表名称的工作簿中

python - 使用 comtypes 保存 PowerPoint 演示文稿时使用文件格式常量

python - 导入 pywinauto(或 comtypes)会破坏现有的 COM 对象

python - 为什么我与 Solr 的连接无法工作?

python - 从 VBA 调用自定义 Python COM 对象

excel - MIME 类型/内容类型,用于在 IE 和 Firefox 中使用 Excel 打开 CSV 文件

python - win32com 内存错误 : CreatingSafeArray attempting to insert data into excel

python - 订阅播客失败 - 想要 2 个参数,而不是 1 个?

excel - 如何让我的循环搜索一个值而不是一串单词?