将多个Excel文件转换为Python中的PDF文件
将其转换为PDF时, win32com 软件包在单个Excel文件上工作正常。但是,当我在循环中运行它以转换多个Excel文件时,它会失败并提供错误消息。 (-2147352567,'
。
from win32com import client
input_file =r"...\input.xlsx"
output_file = r"...\ouput.pdf"
excel = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
Workbook = excel.Workbooks.Open(input_file,None, True)
try:
Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
print("PDF Created successfully!!")
except Exception as e:
print("Failed, try again")
print(str(e))
异常
from win32com import client
import os
directory = "...directory path"
path = os.path.join(directory)
for f in os.listdir(directory):
file_name, file_extension = os.path.splitext(f) #split file name and extention
inputFilePath = directory+ "/" + f
outputFilePath = file_name + '.pdf'
if file_extension == '.xlsx':
excel = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
Workbook = excel.Workbooks.Open(inputFilePath , None, True)
try:
Workbook.ActiveSheet.ExportAsFixedFormat(0, outputFilePath)
print("processing..")
except Exception as e:
print("Failed, try again")
发生 可以做。谢谢!!
The win32com package works fine on a single excel file when converting it into a pdf. But when I run it in a loop to convert multiple excel files, it fails and gives an error message. (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146777998), None)
For single File:-
from win32com import client
input_file =r"...\input.xlsx"
output_file = r"...\ouput.pdf"
excel = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
Workbook = excel.Workbooks.Open(input_file,None, True)
try:
Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
print("PDF Created successfully!!")
except Exception as e:
print("Failed, try again")
print(str(e))
For multiple files:-
from win32com import client
import os
directory = "...directory path"
path = os.path.join(directory)
for f in os.listdir(directory):
file_name, file_extension = os.path.splitext(f) #split file name and extention
inputFilePath = directory+ "/" + f
outputFilePath = file_name + '.pdf'
if file_extension == '.xlsx':
excel = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
Workbook = excel.Workbooks.Open(inputFilePath , None, True)
try:
Workbook.ActiveSheet.ExportAsFixedFormat(0, outputFilePath)
print("processing..")
except Exception as e:
print("Failed, try again")
I would appreciate any suggestions you can make. Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道这个解决方案对您来说可能太晚了。我认为您的问题来自Inputfilepath和OutputFilePath变量。我已经调整了您的代码并正在工作。
``
``
I know that this solution might be too late for you. I think your problem comes from inputfilepath and outputfilepath variables. I've tweaked your code and is working.
`
`