本文介绍了C#使用后关闭Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在应用程序中将Excel用作Com对象.有代码示例
I use Excel as Com object in my application. 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); } }从void退出后,我希望在出现此代码的情况下Excel将从内存中消失
After exiting from void I expect that Excel will disappear from memory in case of this code
finally { excelWorkbook.Close(0); excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); }但不是.直到程序关闭,Excel才存在于内存中.仅在关闭我的应用程序后退出.
but it doesn't. Until program closed Excel exists in memory. It quits only after closing my application.
如何在关闭应用程序之前关闭Excel进程.
How can I close Excel process before I close my application.
p.s.我已阅读此主题在C#中关闭Excel应用程序进程数据访问之后,但没有建议对我有用
p.s. I've read this topic Closing Excel Application Process in C# after Data Access but none of the suggestions work for me
推荐答案
处理完对象后,使用
GC.Collect();这就是我处置Excel对象的方式
This is how I dispose my Excel object
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(); } }更多推荐
C#使用后关闭Excel
发布评论