Convert Excel File to PDF in Python

In this tutorial, we will learn to convert Excel Files to PDF in python. We will learn a bit about PyWin32 library.

PyWin32 is a Python library for Microsoft Windows that enables the Win32 application programming interface (API) features on Python. To install the PyWin32 library, open command prompt/ Terminal and write

pip install pywin32

Approach

Let’s see a fundamental approach to convert Excel files (.xlsx or .xls format) to PDF format.

  • Create a COM object using Dispatch() function.
  • Read the Excel file pass “Excel.Application” inside the Dispatch function.
  • Write Excel file path.
  • Convert Excel into PDF format using ExportAsFixedFormat() and pass the path to which you want to save the pdf file.

Import Client submodule from win32com library

# Import Library
from win32com import client

client.Dispatch() function will help to extract the excel application from windows system. Workbook methods will help to read the excel file.

# Opening Microsoft Excel
excel = client.Dispatch("Excel.Application")

# Read Excel File
sheets = excel.Workbooks.Open('Enter Excel file path')
work_sheets = sheets.Worksheets[0]

Converting Excel file to PDF file. ExportAsFixedFormat() method is used to convert a workbook into either PDF format.

# Converting into PDF File
work_sheets.ExportAsFixedFormat(0, 'Enter PDF file path')

Combining all code

# Import Library
from win32com import client

# Opening Microsoft Excel
excel = client.Dispatch("Excel.Application")

# Read Excel File
sheets = excel.Workbooks.Open('Enter Excel file path')
work_sheets = sheets.Worksheets[0]

# Converting into PDF File
work_sheets.ExportAsFixedFormat(0, 'Enter PDF file path')

We have successfully converted Excel file to PDF file format using Python.

Leave a Reply

Your email address will not be published.