扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
原来书写如下:
以下是引用片段: private Excel.Application m_app; private Excel.Workbook m_workbook; this.m_app = new Excel.ApplicationClass(); this.m_app.DisplayAlerts = false; this.m_workbook = this.m_app.Workbooks.Open(sFilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value ); |
修改后如下:
以下是引用片段: private Excel.Application m_app; private Excel.Workbooks m_workbooks; private Excel.Workbook m_workbook; this.m_app = new Excel.ApplicationClass(); this.m_app.DisplayAlerts = false; m_workbooks = this.m_app.Workbooks; this.m_workbook = this.m_workbooks.Open(sFilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value ); |
同样对Sheet的操作如下
修改前如下:
以下是引用片段: Excel._Worksheet worksheet1 = null; worksheet1 = (Excel._Worksheet) this.m_workbook.Worksheets.get_Item(sSheetName); 修改后如下: Excel.Sheets sheets = null ; Excel._Worksheet worksheet1 = null; sheets = this.m_workbook.Worksheets; worksheet1 = (Excel._Worksheet) sheets.get_Item(sSheetName); |
发现区别了么?原来Workbooks,Worksheets这两个类没有被实例化就直接使用了,造成该类不能够被回收。最终造成Excel在内存的驻留。
最终以如下方式释放。
以下是引用片段: private void ReleaseAllRef(Object obj) { try { if (obj != null ) { while (Marshal.ReleaseComObject(obj) > 1); } } finally { obj = null; } } private void Release() { if (m_app != null ) { m_app.Quit() ; } ReleaseAllRef(m_workbook) ; m_workbook = null ; ReleaseAllRef(m_workbooks) ; m_workbooks = null ; ReleaseAllRef(m_app) ; m_app = null ; System.GC.Collect() ; } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者