Save Excel data in a PDF file in C#


This example extends the example Write Excel data in C#. See that example for information on how to open an Excel workbook, write data into it, and save it.

Note that before you can use the Excel interop library, you need to open the Add References dialog, click the .NET tab, and select Microsoft.Office.Interop.Excel (or whatever version you have installed on your system.)

After opening the workbook and writing data into it as shown in the earlier example, this example uses the following code to save the active worksheet in a PDF file.

// Save into a PDF.
string filename = txtFile.Text.Replace(".xlsx", ".pdf");
const int xlQualityStandard = 0;
    filename, xlQualityStandard, true, false,
    Type.Missing, Type.Missing, true, Type.Missing);

This code converts the Excel workbook’s file name into a file name with the .pdf extension. It then calls the active worksheet’s ExportAsFixedFormat method to export the data in PDF format. If you open the project in Visual Studio, IntelliSense will give you the names of the parameters to ExportAsFixedFormat.

The program then finishes by closing Excel.

Much of the work in this kind of Office automation is figuring out what objects in the Office object model do the things you want. For example, figuring out how to use Word’s InlineShape and Shape objects to create and format the picture. If you want to do a lot of this, my book Microsoft Office Programming: A Guide for Experienced Developers may help. The code is in Visual Basic and it’s a few years, old but it should help you figure out how to manipulate the Word, Excel, PowerPoint, Access, and Outlook object models, and those models haven’t changed much since the book was written.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in Excel, Office and tagged , , , , , , , , , , . Bookmark the permalink.

2 Responses to Save Excel data in a PDF file in C#

  1. Rosey says:

    You can convert/ export excel file to PDF format in C#/.NET by using third party library like Aspose.Cells for .NET. You can try it for free:

  2. Dan Barock says:

    ZetPDF is a C ASP NET VB NET PDF API to create PDF documents from scratch using API or XML PDF library for Windows Forms, WPF and Silverlight as well

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.