Saving an Excel file in a PDF format is very easy in Excel. We can save it in PDF format by exporting it in PDF format from the File -> Export option in Excel but if you want to save an excel file in PDF format using python it is a little bit tough. In this tutorial, we are going to learn how to save/convert excel files in PDF format using python. Before jumping into the coding part make sure you have installed excel and win32.If you have not installed the win32 module yet install it using the following command.
pip install pypiwin32
The DispatchEx method will open a new instance of excel. We can use the Dispatch function instead of DispatchEX as well. The difference is if Excel is already open, Dispatch will create a new tab in the existing excel instance but DispatchEx will open a new excel instance instead of using the existing instance.
The ExpertAsFixedFormat method is used to save a workbook in either PDF or XPS format.
from win32com import client import win32api input_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample.xlsx' #give your file name with valid path output_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample_output.pdf' #give valid output file name and path app = client.DispatchEx("Excel.Application") app.Interactive = False app.Visible = False Workbook = app.Workbooks.Open(input_file) try: Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file) except Exception as e: print("Failed to convert in PDF format.Please confirm environment meets all the requirements and try again") print(str(e)) finally: Workbook.Close() app.Exit()
Now copy the above code and save it and execute it as shown in below snapshot.
The output of this program is the PDF file as shown in below snapshot.