How to convert Excel file to PDF with Python

Published:  

python excel


Describes how to convert an Excel sheet to PDF using Python.
There seem to be many libraries for manipulating Excel files in Python, but this time I will use a module called win32com.

win32com can handle Windows COM objects. Just like using COM objects in Excel VBA.

Environment

  • Windows 10
  • Microsoft Excel 2016
  • Python 3.6.2

Install

win32com is not included by default, so install it.

pip install pywin32

Now you can do import win32com.

Convert Excel file to PDF

I prepared the pre-conversion Excel file (I just brought an Excel template).
One sheet is a calendar for one month, and there are 12 sheets (one year).
Convert this to a single PDF file.

Excel file

Excel file

To convert an Excel file to PDF, simply operate Excel from win32com, open the file and save it as PDF.

The following is a sample program.

import win32com.client
from pywintypes import com_error


# Path to original excel file
WB_PATH = r'C:\hoge\fuga\YearCalendar.xlsx'
# PDF path when saving
PATH_TO_PDF = r'C:\hoge\fuga\YearCalendar.pdf'


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

excel.Visible = False

try:
    print('Start conversion to PDF')

    # Open
    wb = excel.Workbooks.Open(WB_PATH)

    # Specify the sheet you want to save by index. 1 is the first (leftmost) sheet.
    ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
    wb.WorkSheets(ws_index_list).Select()

    # Save
    wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
    print('failed.')
else:
    print('Succeeded.')
finally:
    wb.Close()
    excel.Quit()

All 12 sheets are specified and exported to a PDF file.

The output PDF is as follows.

Output PDF file

Output PDF file

I was able to create PDF more easily than I expected.
It is interesting that there are many other possibilities.

Reference

See also



Related Posts