0
我在我的應用程序中使用Excel作爲Com對象。有代碼示例C#在使用後關閉Excel
public void LoadData()
{
LogHandler logHandler = new LogHandler(Path.GetDirectoryName(FileName) + "\\logfile.log");
string OKATO = GetOKATOFromFileName();
int SubjectId;
if (!int.TryParse(OKATO, out SubjectId))
{
logHandler.WriteLogStr("Ошибка определения ОКАТО из имени файла (" + FileName + ")");
return;
}
int CL;
DateTime FDate = GetDateFromFileName(out CL);
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(FileName,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
try
{
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
for (int i = 1; i <= excelSheets.Count; i++)
{
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(i);
LoadDataFromSheet(excelWorksheet, SubjectId, CL, FDate);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorksheet);
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheets);
}
catch (Exception le)
{
logHandler.WriteLogStr(le.Message);
}
finally
{
excelWorkbook.Close(0);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
}
從虛空退出後我期望的Excel將從內存在這段代碼
finally
{
excelWorkbook.Close(0);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
的情況下消失,但事實並非如此。在程序關閉之前Excel在內存中存在。它只在關閉我的應用程序後退出。
如何在關閉我的應用程序之前關閉Excel過程。
p.s.我讀過這個話題Closing Excel Application Process in C# after Data Access但沒有的建議,爲我的工作
這是否有幫助:http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects – danish
你有沒有使用過這行'System.Runt ime.InteropServices.Marshal.ReleaseComObject(yourcomobjects);'爲你創建的所有對象例如excelWorkbook,excelApp等。 – MethodMan
我已經爲我所有的com變量添加了Marshal.ReleaseComObject,但Excel仍在內存中。 –