The most widely used code to close the Excel process is the following lines.
1System. Runtime. InteropServices. Marshal. ReleaseComObject (r );
2System. Runtime. InteropServices. Marshal. ReleaseComObject (myBook );
3System. Runtime. InteropServices. Marshal. ReleaseComObject (myExcel );
4
5GC. Collect ();
In the past, I often used Excel Development under Winform. I have always been writing programs like this, but I am still happy.
Now I have encountered the Excel format that needs to be done in Webform, and it is a terrible Excel format. I need to add the format, formula, folding, and comments to the program.
Using this code in WebForm will always fail to be closed. There will always be an Excel process.
Later, I discovered that I had to separate the Excel operation code into a method, and then execute GC. Collect () after the method is called.
Put the preceding operations into a CreateExcel method and call the code.
1ExcelBusiness. BSExcel. CreateExcel (filePath );
2GC. Collect ();
In this way, you can immediately close the Excel process after each execution.
GC. collect () is executed in the Excel call method, but the method has not been completed yet, so it is impossible to judge whether the Excel is useless. therefore, the current Excel process cannot be closed. sometimes I see that there will always be an Excel process in this writing system. This is because the last Excel process is useless every time it is executed here, so the last Excel process was closed, but this Excel process always exists. if the GC. collect () This method is written outside the method that calls Excel, you can close it correctly.
Description of this method in MSDN
GC. Collect method () [C #]
Garbage collection is mandatory for all generations.
[C #]
Public static void Collect ();
Remarks
Use this method to reclaim all inaccessible memory. However, the Collect method does not guarantee that all inaccessible memory can be recycled.
Regardless of the duration of the object in the memory, all objects are considered to be recycled. However, objects referenced in managed code are not recycled. Use this method to force the system to try to reclaim the maximum amount of available memory.
In addition, please kindly advise if you have studied Excel in depth.
What if I add a function such as formula and folding to an Excel file in a program?