c# - Excel进程没有关闭

标签 c# .net excel sharepoint pia

我无法在使用完 EXCEL (32) 进程后关闭它。

正如您在下面的代码中看到的,一旦 ProcessRFAFData 函数完成执行,EXCEL 进程并没有关闭(我仍然可以看到 EXCEL.EXE*32 在任务管理器中)。

因此,当 SaveErrors 开始执行时,我得到以下异常:

System.Runtime.InteropServices.COMException (0x800A03EC):   
Microsoft Office Excel cannot open or save any more documents because there is not enough available memory or disk space.   
• To make more memory available, close workbooks or programs you no longer need.   
• To free disk space, delete files you no longer need from the disk you are saving to.  
at Microsoft.Office.Interop.Excel.Workbooks.Add(Object Template)   
at NextG.RFAFImport.Layouts.NextG.RFAFImport.RFAFDataImporter.<>c__DisplayClass9.b__6()   
at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.b__2()   
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)   
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)   
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)  
at NextG.RFAFImport.Layouts.NextG.RFAFImport.RFAFDataImporter.SaveErrors()

这是执行 Excel 进程的代码:

try {
    ProcessRFAFData(FileName);
} catch (Exception ex) {
    Status = "ERROR: " + ex.ToString();
}

if (Errors.Count() > 0) {
    SaveErrors();
}

以下是与 Excel 交互的所有函数:

private void ReleaseObject(object obj) {
    try {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    } catch (Exception) { } finally {
        GC.Collect();
    }
}

private void ProcessRFAFData(string FileName) {
    Microsoft.Office.Interop.Excel.Application XLA = null;
    Microsoft.Office.Interop.Excel.Workbook XLW = null;
    Microsoft.Office.Interop.Excel.Worksheet XLS = null;

    bool error = false;

    try {
        SPSecurity.RunWithElevatedPrivileges(delegate() {
            XLA = new Microsoft.Office.Interop.Excel.Application();
            XLW = XLA.Workbooks.Open(FileName, 0, true,
                Type.Missing, null, null, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                Type.Missing, false, false, Type.Missing, false, Type.Missing, Type.Missing);

            int index = RFAFTabExists(ref XLW);
            if (index == 0) return;

            XLS = (Microsoft.Office.Interop.Excel.Worksheet)XLW.Worksheets.get_Item(index);

            if (!ValidProjectID(ref XLS)) return;

            ParseData(ref XLS);

            XLW.Close(true, Type.Missing, Type.Missing);
            XLA.Quit();

            ReleaseObject(XLS);
            ReleaseObject(XLW);
            ReleaseObject(XLA);
        });
    } catch (SP.ServerException ex) {
        // output error
    } catch (Exception ex) {
        // output error
    }
}

private int RFAFTabExists(ref Microsoft.Office.Interop.Excel.Workbook XLW) {
    int index = 0;
    foreach (Microsoft.Office.Interop.Excel.Worksheet w in XLW.Worksheets) {
        if (w.Name.Equals(settings.Collection["RFAFTabName"])) index++;
    }

    return index;
}

private bool ValidProjectID(ref Microsoft.Office.Interop.Excel.Worksheet XLS) {
    using (SP.ClientContext CTX = new SP.ClientContext(SiteURL)) {
        var projectId = XLS.Cells.get_Range(settings.Collection["ProjectIDCell"], Type.Missing).Text.ToString();

        var project = // getting list of projects from SharePoint

        if (project.Count() > 0) {
            ProjectID = XLS.Cells.get_Range(settings.Collection["ProjectIDCell"], Type.Missing).Text.ToString();
            return true;
        }
    }

    return false;
}

private void ParseData(ref Microsoft.Office.Interop.Excel.Worksheet XLS) {
    ListData.Add("HID", GetHID(XLS.Cells.get_Range(settings.Collection["HIDCell"],
        Type.Missing).Text.ToString()));

    if (ListData["HID"].Equals("0")) Errors.Add(new ImportError {
        Reason = "Hub ID does not exist in this project workspace.",
        Reference = string.Format("Hub ID: {0}", XLS.Cells.get_Range(settings.Collection["HIDCell"],
        Type.Missing).Text.ToString())
    });

    int row = Int32.Parse(settings.Collection["StartRow"]);
    while (!NoMoreData(ref XLS, row)) {
        string PRSIN = XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["PRSIN"], row), Type.Missing).Text.ToString();

        string NOC = ValidateNumber(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["NOC"], row), Type.Missing).Text.ToString());

        string UEIRP = ValidateNumber(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["UEIRP"], row), Type.Missing).Text.ToString());

        string LAT = ValidateLatLon(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["LAT"], row), Type.Missing).Text.ToString());

        string LON = ValidateLatLon(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["LON"], row), Type.Missing).Text.ToString());

        string PJ = GetPJ(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["JurisdictionCol"], row), Type.Missing).Text.ToString(),
            XLS.Cells.get_Range(string.Format("{0}{1}", settings.Collection["StateCol"], row),
            Type.Missing).Text.ToString());

        string ST = GetState(XLS.Cells.get_Range(string.Format("{0}{1}",
            settings.Collection["JurisdictionCol"], row), Type.Missing).Text.ToString(),
            XLS.Cells.get_Range(string.Format("{0}{1}", settings.Collection["StateCol"], row),
            Type.Missing).Text.ToString());

        ListItemData.Add(new ListItem {
            ProposedRemoteSiteItemNumber = PRSIN,
            NumberOfCarriers = NOC,
            UsableEIRP = UEIRP,
            Latitude = LAT,
            Longitude = LON,
            PrimaryJurisdiction = PJ,
            State = ST
        });

        row++;
    }
}

private bool NoMoreData(ref Microsoft.Office.Interop.Excel.Worksheet XLS, int row) {
    return string.IsNullOrEmpty(XLS.Cells.get_Range(string.Format("{0}{1}",
        settings.Collection["ProposedRemoteSiteItemNumberCol"], row), Type.Missing).Text.ToString());
}

private void SaveErrors() {
    Microsoft.Office.Interop.Excel.Application XLA = null;
    Microsoft.Office.Interop.Excel.Workbook XLW = null;
    Microsoft.Office.Interop.Excel.Worksheet XLS = null;

    object MissingValue = System.Reflection.Missing.Value;

    try {
        try {
            SPSecurity.RunWithElevatedPrivileges(delegate() {
                XLA = new Microsoft.Office.Interop.Excel.Application();
                XLW = XLA.Workbooks.Add(MissingValue);
                XLS = (Microsoft.Office.Interop.Excel.Worksheet)XLW.Worksheets.get_Item(1);

                XLS.Cells[1, 1] = "Reason for error";
                XLS.Cells[1, 2] = "Reference";

                XLS.get_Range("A1").Font.Bold = true;
                XLS.get_Range("B1").Font.Bold = true;

                int row = 2;
                foreach (ImportError e in Errors) {
                    XLS.Cells[row, 1] = e.Reason;
                    XLS.Cells[row, 2] = e.Reference;

                    row++;
                }

                XLW.SaveAs(ErrorLogFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                    MissingValue, MissingValue, MissingValue, MissingValue,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, MissingValue,
                    MissingValue, MissingValue, MissingValue, MissingValue);

                XLW.Close(true, MissingValue, MissingValue);
                XLA.Quit();

                ReleaseObject(XLS);
                ReleaseObject(XLW);
                ReleaseObject(XLA);
            });
        } catch (Exception ex) {
            Status = "ERROR: " + ex.ToString();
        }

        // Uploading excel file to SharePoint document library

    } catch (Exception) { }
}

最佳答案

你可能要离谱了explicit :

excelWorkbook.Close (false, System.Reflection.Missing.Value,System.Reflection.Missing.Value) ;   
excelWorkbooks.Close();  
excelApp.Quit();  
Marshal.ReleaseComObject(excelWorksheet);  
Marshal.ReleaseComObject(excelSheets);  
Marshal.ReleaseComObject(excelWorkbooks);  
Marshal.ReleaseComObject(excelWorkbook);  
Marshal.ReleaseComObject(excelApp);  
excelWorksheet = null;  
excelSheets = null;  
excelWorkbooks = null;  
excelWorkbook = null;  
excelApp = null;  
GC.GetTotalMemory(false);  
GC.Collect();  
GC.WaitForPendingFinalizers();  
GC.Collect();  
GC.GetTotalMemory(true);  

我遇到过即使那样也做不到的情况。我求助于寻找 Excel 进程并在其上调用 Kill()。

关于c# - Excel进程没有关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6960693/

相关文章:

c# - 桌面上的 UWP 全局 MessageDialog

c# - 是否可以防止 foreach 展平矩形阵列?

c# - 如何在 VS 2013 中更改预览中的程序名称?

.net - 为什么 Lazy.CreateFromValue 的行为在 .NET 框架版本之间的 F# 中发生了变化?

c# - IDisposable 对象是否在使用 RequestContainer 的 Nancy 请求结束时被释放?

c# - 是否有实时 IIS 流量查看器(或通过 C# 以编程方式获取它的方式)

java - 等同于 Java 中的 CryptoStream .NET?

excel - 如何让图像出现在给定图像 url 的 Excel 中

r - 将数据集的列批量更改为数字

excel - 如何从 CSV 数据创建图表