C#Winform如何正确配置Excel / Interop? [英] C# Winform How to Properly Dispose Excel / Interop?

查看:82
本文介绍了C#Winform如何正确配置Excel / Interop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,这是场景:



我使用datagridview将数据导出到Excel,经过多次导出后,我注意到我的电脑变慢了,检查进程,我发现运行的Excel.exe太多了。我所做的是关闭了应用程序并删除了该过程。



我的问题是,如何正确处理Excel,导出数据后,所以我不会每次都退出我的应用程序。我的代码如下:



Hello, here's the scenario:

Im using datagridview to export data to Excel, after many times of exporting, i have noticed that my computer become slow, and check the Processes and i saw that there's too many Excel.exe running. What i did is I closed the Application and it removes on the process.

My Question is, how to properly dispose the Excel, After exporting data, so i wont quit my application everytime. My code below:

Microsoft.Office.Interop.Excel._Application Excel = new Microsoft.Office.Interop.Excel.Application();

                  Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);

                  Worksheet ws = (Worksheet)Excel.ActiveSheet;

                  //ws.PageSetup.Zoom = false;

                  //ws.PageSetup.FitToPagesTall = 1;
                  //ws.PageSetup.FitToPagesWide = 1;

                  Excel.Visible = true;

                  ws.Cells.EntireColumn.AutoFit();
                  ws.Cells.EntireRow.AutoFit();
                  ws.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; // Align cells to lef (excel)(



请使用我的代码进行修订。谢谢


Please use my code for the revision . thanks

推荐答案

尝试如何正确发布Excel COM对象:C#代码示例 [ ^ ]。


EXCEL和WORD是非常非托管的对象,所以GC无法收集它们在EXCEL情况下我们首先需要使用'Marshal.ReleaseComObject'方法释放COM对象或每张表然后我们需要首先处理EXCEL工作簿然后退出EXCEL应用程序对象

见下面的清理组

EXCEL and WORD are very and unmanaged objects, so GC is unable to collect them In EXCEL case first we need to we need to use 'Marshal.ReleaseComObject' method to release COM object or each sheet and then we need to dispose EXCEL Workbook first and then quit to EXCEL application object
see below cleanup group
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);

xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);


由于您使用过 Excel.Visible = true ,excel将在屏幕上显示给用户。那么如何处理屏幕上的excel取决于用户。用户可以保存并关闭它,也可以不保存就丢弃它。当用户关闭excel程序时,该过程也应该被关闭/终止。
Since you have used Excel.Visible = true, excel will be visible to the user on screen. So what to do with the excel on screen is up to the user. User can either save it and close it or just discard it without saving. And when the user closes the excel the program, the process also should be closed/terminated.


这篇关于C#Winform如何正确配置Excel / Interop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆