Search code examples
c#excel-2007

Excel ExportAsFixedFormat PDF


I can successfully take an excel file and export it as a PDF file in c#

private static void ExportWorkbookToPDF(string workbook, string output)
{
    if (string.IsNullOrEmpty(workbook) || string.IsNullOrEmpty(output))
    {
        throw new NullReferenceException("Cannot create PDF copy " +
            "from empty workbook.");
    }

    Application excelApplication = new Application();
    excelApplication.ScreenUpdating = false;
    excelApplication.DisplayAlerts = false;
    excelApplication.Visible = false;

    Workbook excelWorkbook = excelApplication.Workbooks.Open(
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + 
        "\\" + workbook);

    if (excelWorkbook == null)
    {
        excelApplication.Quit();
        excelApplication = null;
        excelWorkbook = null;

        throw new NullReferenceException("Cannot create new excel workbook.");
    }

    try
    {
        excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, 
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + 
            "\\" + output);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
    finally
    {
        excelWorkbook.Close();
        excelApplication.Quit();
        excelApplication = null;
        excelWorkbook = null;
    }
}

What parameter or object do I need to access in order to save the excel file as page width instead of page height?


Solution

  • I have found the property required to force the export of your workbook in a PDF with Landscape view.

    try 
    { 
        ((Microsoft.Office.Interop.Excel._Worksheet)  
        excelWorkbook.ActiveSheet).PageSetup.Orientation =  
        Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
    
        excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF,  
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + 
            "\\" + output); 
    }