使用Microsoft.interop.Excel.dll时System.Runtime.InteropServices.COMException

时间:2015-09-17 11:17:57

标签: c# excel

我使用Microsoft.interop.Excel.dll将Excel转换为.pdf。核心代码:

using Microsoft.Office.Interop.Excel;
using ExcelApplicationClass =        Microsoft.Office.Interop.Excel.ApplicationClass;

public static bool ExcelToPdf(string sourcePath, string targetPath, out string exmsg)
    {

        exmsg = string.Empty;
        bool result = false;
        object missing = Type.Missing;

        ExcelApplicationClass applicationClass = null;

        Workbook workBook = null;
        try
        {
            applicationClass = new ExcelApplicationClass();               
            applicationClass.Visible = false;
           /* applicationClas*/
            workBook = applicationClass.Workbooks.Open(sourcePath);


            if (workBook != null)
            {

                Microsoft.Office.Interop.Excel.Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
                //*** if I annotation the block in this if. the code no error occured.
                if (worksheet != null)
                {
                    worksheet.PageSetup.Zoom = false;
                    worksheet.PageSetup.FitToPagesWide = 1;                    

                }

                workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath, XlFixedFormatQuality.xlQualityMinimum, false, true);

            }
            result = true;
        }
        catch (Exception ex)
        {
            exmsg = ex.Message;
            result = false;
        }
        finally
        {
            if (workBook != null)
            {
                workBook.Close(true,missing, missing);
                workBook = null;
            }
            if (applicationClass != null)
            {
                applicationClass.Quit();
                applicationClass = null;
            }
        }
        return result;
    }

如果我没有将worksheet.PageSetup's属性设置为zoom等,那么该程序运行良好,但如果我设置属性System.Runtime.InteropServices.COMException将会出现9次。有时候没有错误。

错误信息

enter image description here

环境信息

  • Microsoft Excel 2013

  • Windows 10

  • 每次杀死Microsoft Excel进度。

0 个答案:

没有答案