0

I use code from this thread Print chosen worksheets in excel files to pdf in python to convert Excel file to Pdf.

It was working fine and suddendly, it now give me error below at this line wb.WorkSheets(ws_index_list).Select()

(The code opens Excel file fine)

AttributeError: '<win32com.gen_py.Microsoft Excel 16.0 Object Library._Workbook instance at 0x2758034291872>' object has no attribute 'WorkSheets'

---> 21 wb.WorkSheets(ws_index_list).Select() 22 wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)

import win32com.client
o = win32com.client.Dispatch("Excel.Application")
# o = win32.gencache.EnsureDispatch('Excel.Application')
o.Visible = False

# Path to Excel file
wb_path = r'~\Sample Invoice1.xlsx'

wb = o.Workbooks.Open(wb_path)
print('type of wb:',type(wb))
 
    
ws_index_list = [1] #say you want to print these sheets

path_to_pdf = r'~/Sample Invoice1.pdf'
wb.WorkSheets(ws_index_list).Select()
wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf) 
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Harry
  • 109
  • 7

1 Answers1

2

Looks like the attribute is called Sheets and not WorkSheets.

So you'll change your second-to-last-line to:

wb.Sheets(ws_index_list.Select()
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29
  • Also, you'll want to make sure you quit everything when you are done. That is, you probably want to add `wb.Close()` and `o.Quit()` to the end of it all. – scotscotmcc Nov 28 '21 at 03:00