Convert Excel to PDF Using Python and Spire.XLS
This tutorial explains how to install the Spire.XLS library, import its modules, and use Python code examples to convert entire Excel workbooks, individual worksheets, or specific sheets with custom page settings into PDF files for consistent document sharing.
Converting Excel files to PDF ensures consistent layout across devices and is useful for storage, printing, and sharing.
This guide shows how to use the third‑party Python library Spire.XLS to perform the conversion.
Step 1: Install the library with pip install Spire.XLS .
Step 2: Import the required modules:
from spire.xls import *
from spire.common import *Step 3: Load the workbook and save it as PDF using Workbook.SaveToFile(..., FileFormat.PDF) or Worksheet.SaveToPdf(...) . Page settings can be adjusted via the PageSetup class.
Example 1 – Convert each worksheet to a separate PDF page:
from spire.xls import *
from spire.common import *
# Create Workbook object
workbook = Workbook()
# Load Excel file
workbook.LoadFromFile("data.xlsx")
# Fit each sheet to page
workbook.ConverterSetting.SheetFitToPage = True
# Save to PDF
workbook.SaveToFile("ToPDF.pdf", FileFormat.PDF)
workbook.Dispose()Example 2 – Save each worksheet as an individual PDF file:
from spire.xls import *
from spire.common import *
workbook = Workbook()
workbook.LoadFromFile("data.xlsx")
for sheet in workbook.Worksheets:
FileName = sheet.Name + ".pdf"
sheet.SaveToPdf(FileName)
workbook.Dispose()Example 3 – Convert a specific worksheet with custom page margins and paper size:
from spire.xls import *
from spire.common import *
workbook = Workbook()
workbook.LoadFromFile("data.xlsx")
sheet = workbook.Worksheets[1]
pageSetup = sheet.PageSetup
pageSetup.TopMargin = 0.3
pageSetup.BottomMargin = 0.3
pageSetup.LeftMargin = 0.3
pageSetup.RightMargin = 0.3
pageSetup.PaperSize = PaperSizeType.PaperA3
workbook.ConverterSetting.SheetFitToPage = True
sheet.SaveToPdf("ExcelWorksheetToPDF.pdf")
workbook.Dispose()Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.