Trying To Convert Excel Sheets To Pdf Using Python But Throwing Up This Error
Hi I am trying to convert excel sheet to pdf using python, converted a script wrote to do same with word documents, which works fine but having this error below flagging up Traceba
Solution 1:
You can try with win32com.client
like this:
import win32com.client
from pywintypes import com_error
WB_PATH = r'C:\Users\alank\Python training\Helloworld.xlsx'
PATH_TO_PDF = r'C:\Users\alank\Python training\Helloworld.pdf'
excel.Visible = Falsetry:
# Open
wb = excel.Workbooks.Open(WB_PATH)
# Specify the sheet you want to save by index. #if you want all the sheets in excel try with: #wb.WorkSheets(wb.Sheets.Count) or wb.WorkSheets([i=1 for i in range(wb.Sheets.Count)]).Select()
ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
wb.WorkSheets(ws_index_list).Select()
# Save
wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
print('The convertion failed.')
else:
print('Succeessful convertion')
finally:
wb.Close()
excel.Quit()
Or you can do it like here (Andreas solution):
import os
import comtypes.client
SOURCE_DIR = r'C:\Users\alank\Python training'
TARGET_DIR = r'C:\Users\alank\Python training'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'Helloworld.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'Helloworld.pdf')
doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()
app.Quit()
Post a Comment for "Trying To Convert Excel Sheets To Pdf Using Python But Throwing Up This Error"