printing xlsx to pdf in csharp

To convert an XLSX file to a PDF file in C#, you can use the Excel Interop library to open the XLSX file and print it to a PDF printer (such as the Microsoft Print to PDF driver). Here's an example of how to do this:

main.cs
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;

public static void ConvertXLSToPDF(string xlsxFilePath, string pdfFilePath)
{
    // Create a new instance of the Excel application
    Excel.Application excelApp = new Excel.Application();
    try
    {
        // Open the XLSX file
        Excel.Workbook workbook = excelApp.Workbooks.Open(xlsxFilePath);

        // Print the workbook to PDF
        workbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfFilePath);

        // Close the workbook and release resources
        workbook.Close(false);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
        workbook = null;

        // Quit Excel and release resources
        excelApp.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        excelApp = null;
    }
    catch (IOException ex)
    {
        // Handle any IO exceptions
        Console.WriteLine("Error converting XLSX to PDF: " + ex.Message);
    }
}
1006 chars
32 lines

This code opens the XLSX file using the Excel Interop library, prints it to a PDF file using the ExportAsFixedFormat method, and then releases all of the resources used by Excel. Note that you will need to add a reference to the Microsoft Excel Object Library in your C# project to use the Excel Interop library.

gistlibby LogSnag