Convert Excel to PDF with Python: Step‑by‑Step Guide Using Spire.XLS
This guide shows how to install the Spire.XLS for Python library and use its Workbook and Worksheet classes to convert Excel files—or individual worksheets—into PDF documents, including page‑setup options and examples for saving each sheet as a separate PDF.
Converting Excel files to PDF makes it easy to store spreadsheet data and ensures consistent layout when printing or sharing across devices and operating systems.
Steps to convert Excel to PDF in Python
1. Install the required library via pip: pip install Spire.XLS 2. Import the necessary modules:
from spire.xls import *
from spire.common import *3. Load the Excel document and use Workbook.SaveToFile() or Worksheet.SaveToPdf() to convert the workbook or a specific worksheet to PDF.
4. Optional page settings can be adjusted through the PageSetup class.
Example 1: Convert an entire Excel file to a single PDF (each worksheet on a separate 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 as PDF
workbook.SaveToFile("ToPDF.pdf", FileFormat.PDF)
workbook.Dispose()Example 2: Convert each worksheet to a separate 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 to PDF with custom page settings
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()Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
