The PDF format is one of the most widely used document formats for sharing documents. This tutorial will show you how to use C# to convert Excel to PDF. In this article, we’ll convert an Excel workbook to a PDF document using the XLSX format. Additionally, you can swiftly convert Excel to PDF using C# for various Excel formats such as XLS, CSV, XLT, and many others with just a few lines of code. Furthermore, no third-party software is required for the conversion.
Steps to Convert Excel to PDF in C#
- Install GroupDocs.Conversion for .NET from the NuGet to convert Excel to PDF using C#
- Add reference to GroupDocs.Conversion namespace
- Create an instance of the Converter class and load the input Excel for conversion to PDF
- Initialize PdfConvertOptions class for providing preferences for the PDF document
- Call the Convert method of the Converter class and pass the name of the output PDF file along with the object of PdfConvertOptions class
These steps are self-explanatory and can be used in your project right away to convert Excel file to PDF using C#. To begin, use the NuGet package manager to install the necessary library. After that, create a Converter class instance and load the Excel file to be converted to a PDF. Finally, you can adjust the settings for the converted PDF file and save it to disc.
Code to Convert Excel to PDF in C#
using System; | |
using GroupDocs.Conversion.Options.Convert; | |
namespace ConvertExcelToPdfInCSharp | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) // Main function to convert Excel to PDF using C# | |
{ | |
// Remove the watermark in output PDF document by adding license | |
string licensePath = "GroupDocs.Conversion.lic"; | |
GroupDocs.Conversion.License lic = new GroupDocs.Conversion.License(); | |
lic.SetLicense(licensePath); | |
// Load the source Excel file for conversion to PDF | |
var converter = new GroupDocs.Conversion.Converter("sample.xlsx"); | |
// Set the starting sheet number and consecutive sheet count | |
var convertOptions = new PdfConvertOptions() | |
{ | |
PageNumber = 1, | |
PagesCount = 2 | |
}; | |
// Convert and save the Excel in PDF format | |
converter.Convert("converted.pdf", convertOptions); | |
Console.WriteLine("Done"); | |
} | |
} | |
} |
In this article, we learned how to convert files using C# Excel to PDF code. We looked at both the basic and advanced conversion cases by setting page setup attributes. Additionally, Excel workbooks can be simply converted to HTML, Microsoft PowerPoint, and Word formats.
We discussed the convert Image to PDF in C# code in our earlier article. If you’re interested, have a look at it.