Python is a high-level, general-purpose programming language that is widely used. Python programming language is utilized in web development, machine learning applications, and all cutting-edge software technologies.

Now let us see how to convert Excel file to PDF.

pywin32 Module:

The pywin32 package has been available for quite some time. In fact, Mark Hammond and Andy Robinson published a book on the subject in 2000. Despite the fact that it is 18 years old (which makes me feel really old:), the underlying technology and concepts are still functional today. Pywin32 is a very thin Python wrapper that allows us to interact with COM objects and automate Windows applications using Python. The power of this approach is that you can use Python to do almost anything that a Microsoft application can do. The disadvantage is that this must be run on a Windows system with Microsoft Office installed.

Installation

pip install pywin32

ExportAsFixedFormat() Function:

To publish a workbook in either PDF or XPS format, use the ExportAsFixedFormat() function.

Syntax:

ExportAsFixedFormat (Type, File_name, Quality, IncludeDocProperties, IgnorePrintAreas, 
From, To, OpenAfterPublish, FixedFormatExtClassPtr)

Program to Convert Excel to PDF in Python

Approach:

  • Import client that belongs to win32com module using the import keyword.
  • Pass “Excel.Application” as an argument client.Dispatch() function to the Create COM object(Opening Microsoft Excel).
  • Open the Excel file by Passing the Excel file path as an argument to the Open() method.
  • Open the first worksheet using the Worksheets[0] and store it in another variable.
  • Convert the above Excel file to PDF File using the ExportAsFixedFormat() function by passing 0, PDF file path as arguments to it.
  • The Exit of the Program.

Below is the implementation:

# Import client that belongs to win32com module using the import keyword
from win32com import client
  
# Pass "Excel.Application" as an argument client.Dispatch() function 
# to the Create COM object(Opening Microsoft Excel)
# Store it in a variable.
excel_file = client.Dispatch("Excel.Application")
  
# Open the Excel file by Passing the Excel file path as an argument to the Open() method
xl_sheets = excel_file.Workbooks.Open(r'C:\Users\vicky\Downloads\demo.xlsx')
# Open the first worksheet using the Worksheets[0]
# Store it in another variable.
worksheets = xl_sheets.Worksheets[0]
  
# Convert the above Excel file to PDF File using the ExportAsFixedFormat() 
# function by passing 0, PDF file path as arguments to it.
worksheets.ExportAsFixedFormat(0, r'C:\Users\vicky\Downloads\demo.pdf')

Outputs:

Excel File Image:

Program to Convert Excel to PDF in Python

Folder Image:

Program to Convert Excel to PDF in Python - Folder

Pdf Screenshot:

Convert Excel to PDF using Python Code

Leave a Reply

Your email address will not be published.