Common. NET function code Summary (3)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.