8

我可以成功获取一个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 文件保存为页面宽度而不是页面高度,我需要访问哪些参数或对象?

4

3 回答 3

17

我找到了强制将工作簿导出为具有横向视图的 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); 
} 
于 2012-04-22T23:06:22.660 回答
4
  1. 安装 2007 Microsoft Office Suite 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

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

这对我有用。

于 2014-07-07T07:29:27.567 回答
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调整页面大小。

于 2013-12-17T12:32:06.373 回答