C#使用后关闭Excel

编程入门 行业动态 更新时间:2024-10-24 01:48:19
本文介绍了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

本文发布于:2023-11-17 07:28:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!