In enterprise applications, programmatically converting Excel documents to PDF format is a common task. PDF ensures a document’s layout remains consistent across different devices and does not require the recipient to have spreadsheet software installed.
This article walks through how to convert Excel (XLS/XLSX) files to PDF in C# using the Spire.XLS for .NET library. It covers basic conversion, exporting specific sheets, fitting content to one page, customizing page setup, and adding PDF security.
Why Convert Excel to PDF?
Preserved Formatting – PDF locks layout, fonts, and images.
Cross-Platform Compatibility – PDF readers are widely available.
Optional Security – PDF can be encrypted or password-protected.
Setting Up the Environment
Install the Spire.XLS for .NET library via NuGet Package Manager:
Install-Package Spire.XLSOnce installed, add the namespace at the top of your code file:
using Spire.Xls;The library does not require Microsoft Excel to be installed on the server.
1. Basic Excel to PDF Conversion
The following code loads an entire Excel workbook and saves it as a single PDF file.
using Spire.Xls;
namespace ExcelToPdf.Basic
{
class Program
{
static void Main(string[] args)
{
using (Workbook workbook = new Workbook())
{
// Load an Excel file (.xls or .xlsx)
workbook.LoadFromFile("Sample.xlsx");
// Save the workbook as a PDF
workbook.SaveToFile("Output/BasicConversion.pdf", FileFormat.PDF);
}
System.Console.WriteLine("Conversion completed.");
}
}
}Explanation:
Workbookrepresents the entire Excel file.LoadFromFileloads an existing Excel file from disk.SaveToFilewithFileFormat.PDFtriggers the conversion.
2. Advanced Customizations
A. Exporting a Specific Worksheet or Cell Range
To export only one sheet or a defined cell range:
using Spire.Xls;
namespace ExcelToPdf.Advanced
{
class Program
{
static void Main(string[] args)
{
using (Workbook workbook = new Workbook())
{
workbook.LoadFromFile("SalesData.xlsx");
// Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Define a print area (e.g., cells B1 to E6)
// If omitted, the entire sheet is exported.
worksheet.PageSetup.PrintArea = "B1:E6";
// Save this specific sheet/range to PDF
worksheet.SaveToPdf("Output/SpecificSheet.pdf");
}
}
}
}
Join the conversation! Your thoughts help the community grow.