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!!
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.
`
from win32com import client
import os
directory = r"....directory path...."
for file in os.listdir(directory):
file_name, file_extension = os.path.splitext(file) # split file name and extension
input_file_path = os.path.join(directory, file)
output_file_path = os.path.join(directory, file_name + '.pdf')
if file_extension == '.xlsx' or file_extension == '.xls':
excel = client.DispatchEx("Excel.Application")
excel.Interactive = False
excel.Visible = False
workbook = excel.Workbooks.Open(input_file_path, None, True)
workbook.ActiveSheet.ExportAsFixedFormat(0, output_file_path)
`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.