How to convert excel to pdf in C#.


To use this code excel component must be installed on the system on which application will run.
Add reference to excel Interop in the application. Import the Excel Interop in application.

using Microsoft.Office.Interop.Excel;
private void getExcelToPDF(string ExcelPath, string PDFPath)
{
    Application ExcelApp;
    Workbooks ExcelWorkbooks = null;
    Workbook ExcelWorkbook = null;
    try
    {
        object misValue = System.Reflection.Missing.Value;
        ExcelApp = new Application();
        ExcelApp.Visible = false;
        object varMissing = Type.Missing;
        ExcelWorkbooks = ExcelApp.Workbooks;

        //if file already exist then delete the file
        if (System.IO.File.Exists(PDFPath))
        {
            System.IO.File.Delete(PDFPath);
        }
        ExcelWorkbook = ExcelWorkbooks.Open(ExcelPath, misValue, misValue,
                                                misValue, misValue, misValue, misValue, misValue, misValue,
                                                misValue, misValue, misValue, misValue, misValue, misValue);
        ExcelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, PDFPath,
                                            XlFixedFormatQuality.xlQualityStandard,
                                            varMissing, false, varMissing, varMissing, false, varMissing);
        ExcelWorkbooks.Close();
        ExcelApp.Quit();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        ExcelApp = null;
    }
}