Print chosen worksheets in excel files to pdf in python

This seems like the place to put this answer.

In the simplest form:

import win32com.client

o = win32com.client.Dispatch("Excel.Application")

o.Visible = False

wb_path = r'c:\user\desktop\sample.xls'

wb = o.Workbooks.Open(wb_path)



ws_index_list = [1,4,5] #say you want to print these sheets

path_to_pdf = r'C:\user\desktop\sample.pdf'



wb.WorkSheets(ws_index_list).Select()

wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)

Including a little formatting magic that scales to fit to a single page and sets the print area:

import win32com.client

o = win32com.client.Dispatch("Excel.Application")

o.Visible = False

wb_path = r'c:\user\desktop\sample.xls'

wb = o.Workbooks.Open(wb_path)



ws_index_list = [1,4,5] #say you want to print these sheets

path_to_pdf = r'C:\user\desktop\sample.pdf'

print_area="A1:G50"



for index in ws_index_list:

    #off-by-one so the user can start numbering the worksheets at 1

    ws = wb.Worksheets[index - 1]

    ws.PageSetup.Zoom = False

    ws.PageSetup.FitToPagesTall = 1

    ws.PageSetup.FitToPagesWide = 1

    ws.PageSetup.PrintArea = print_area



wb.WorkSheets(ws_index_list).Select()

wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)

I have also started a module over a github if you want to look at that: https://github.com/spottedzebra/excel/blob/master/excel_to_pdf.py

Leave a Comment