Excel ExportAsFixedFormat PDF

时间:2012-04-22 21:49:22

标签: c# excel-2007

我可以成功获取excel文件并将其导出为c#

中的PDF文件
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;
    }
}

为了将excel文件保存为页面宽度而不是页面高度,我需要访问哪些参数或对象?

3 个答案:

答案 0 :(得分:13)

我找到了强制将您的工作簿导出到带有横向视图的PDF中所需的属性。

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); 
} 

答案 1 :(得分:4)

  1. 安装2007 Microsoft Office套件Service Pack 3(SP3) http://www.microsoft.com/en-in/download/details.aspx?id=27838

  2. 安装2007 Microsoft Office加载项:Microsoft另存为PDF或XPS http://www.microsoft.com/en-in/download/details.aspx?id=7

  3. 必填: Microsoft XPS Document Writer 设置为服务器中的默认打印机。 因为 ExportAsFixedFormat 函数执行 Microsoft XPS Document Writer 以将Excel转换为PDF。

    这对我有用。

答案 2 :(得分:1)

请试试这个:

object misValue = System.Reflection.Missing.Value;
string paramExportFilePath = @"C:\Test2.pdf";
Excel.XlFixedFormatType paramExportFormat = Excel.XlFixedFormatType.xlTypePDF;
Excel.XlFixedFormatQuality paramExportQuality = Excel.XlFixedFormatQuality.xlQualityStandard;
bool paramOpenAfterPublish = false;
bool paramIncludeDocProps = true;
bool paramIgnorePrintAreas = true;
if (xlWorkBook != null)//save as pdf
    xlWorkBook.ExportAsFixedFormat(paramExportFormat, paramExportFilePath, paramExportQuality,     paramIncludeDocProps, paramIgnorePrintAreas, 1, 1, paramOpenAfterPublish, misValue);

参数paramIgnorePrintAreas=true调整页面大小。