[英]C# closing Excel after using
I use Excel as Com object in my application. 我在应用程序中使用Excel作为Com对象。 There is code example 有代码示例
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);
}
}
After exiting from void I expect that Excel will disappear from memory in case of this code 从void退出后,如果出现此代码,我希望Excel从内存中消失
finally
{
excelWorkbook.Close(0);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
but it doesn't. 但事实并非如此。 Until program closed Excel exists in memory. 直到程序关闭,Excel才存在于内存中。 It quits only after closing my application. 它仅在关闭我的应用程序后退出。
How can I close Excel process before I close my application. 关闭应用程序之前,如何关闭Excel进程。
ps I've read this topic Closing Excel Application Process in C# after Data Access but none of the suggestions work for me ps我已经阅读了本主题,在数据访问后在C#中关闭Excel应用程序进程,但是没有任何建议对我有用
When you done disposing the object, use 处理完对象后,请使用
GC.Collect();
This is how I dispose my Excel object 这就是我处置Excel对象的方式
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.