33. Close the Excel process completely
. NET using Excel belongs to the use of unmanaged resources, the use of the completion of the general will use GC recycling resources, but the location of the call GC is not correct, the Excel process may not completely shut down, such as the following code:
Static voidOpenexceltest (intj) {//application Excel = null;Excel =Newapplication (); Excel. Visible=true; Excel. Workbooks.Open ("D:\\a1000.xla"); Workbook WB= Excel. Application.Workbooks.Open ("d:\\book1.xlsx"); Worksheet SH= WB. worksheets.item["Sheet1"]; Object[,] ssss = sh. Range[sh. cells[1.1], Sh. cells[3,1]]. Value2; Console.WriteLine ("opened Excel No. {0}", J); Console.ReadLine (); Try { //try the program to close the Excel processWb. Close (false); SH=NULL; WB=NULL; Excel. Quit (); } Catch(Exception ex) {Console.WriteLine ("the user has manually ended the Excel process with an internal error message: {0}", ex. Message); } intGeneration =System.GC.GetGeneration (Excel); // the//System.Runtime.InteropServices.Marshal.ReleaseComObject (WB); //System.Runtime.InteropServices.Marshal.ReleaseComObject (SH); //System.Runtime.InteropServices.Marshal.ReleaseComObject (Excel);Excel=NULL; //No.2//GC. Collect (generation);Console.WriteLine ("close Excel No. {0}", J); Console.ReadLine (); }
In the above code, if the comment at the no.1,no.2 location is canceled, the Excel process cannot be completed after the method ends, and the workaround is to simply
Gc. Collect ();
This line of code is written outside of the method.
application Excel = NULL;
This Excel Application object definition is possible inside or outside the method, even if a static variable is defined, the result has no effect.
Common. NET function code Summary (3)