Hey Guys! hope you're having an awesome day, please help :)
I need to print a specific sheet to PDF out of every Excel file in a dir of thousands.
I keep getting the same error, the first file prints perfectly but when the script advance to the second file I get this error msg:
File "<COMObject >", line 5, in ExportAsFixedFormat com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147018887), None)
- The excel version is 2010
- I have already printed and checked the list, it seems legit
here is the code I use:
import win32com.client
import os
sheet_list = []
for file in os.listdir('C:/Users/Guy/Documents/P'):
if file.endswith('.xlsm'):
sheet_list.append(file)
path = ('C:/Users/Guy/Documents/P/')
file_list = [path + x for x in sheet_list]
def SheetPrint(wb_path):
o = win32com.client.Dispatch("Excel.Application")
o.Visible = False
wb = o.Workbooks.Open(wb_path)
ws_index_list = [2] #say you want to print these sheets
num = 1
pdf_path = ('C:/Users/Guy/Documents/P/pdf/'+str(num))
print_area = 'A1:G50'
wb.WorkSheets(ws_index_list).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path )
wb.WorkSheets(1).Select()
wb.Close(True)
num = (num + 1)
for i in file_list:
SheetPrint(i)
the code was inspired by this post: Print chosen worksheets in excel files to pdf in python