简体   繁体   中英

Problem in opening Excel files externally during execution of a C# application

I have created a C# application whose inputs are some large Excel files.

In my code, I open it, process and then close it. The whole process takes some 15-20 minutes. During this time when I try to open some other Excel files(1) externally, anyone of the input Excel files(2) (which is currently being processed) is also getting opened along with this. When I try to close this(2), exception occurs and the tool aborts its process.

I think the problem occurs because the Excel files are opened under the same instance. How can I avoid this?

The following is the code:

Excel.ApplicationClass objExcelApp = new Excel.ApplicationClass();
Excel.Workbook objWorkbook = objExcelApp.Workbooks.Open("File Name",0, true, 1, "", "", true, Excel.XlPlatform.xlWindows,Type.Missing, false, false, 0,true);
Excel.Worksheet objWorksheet = (Excel.Worksheet) objWorkbook.Worksheets.get_Item(1);
Excel.Range objRangeData =objWorksheet.UsedRange;
// Some proces
GC.Collect();
objRangeData.Clear ();
objWorkbook.Close(false, strDictFile, false);
objExcelApp.Workbooks.Close();
objExcelApp.Quit();             
System.Runtime.InteropServices.Marshal.ReleaseComObject(objRangeData); 
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorksheet);          
System.Runtime.InteropServices.Marshal.ReleaseComObject(objWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcelApp); 
objWorksheet = null; 
objWorkbook = null; 
objExcelApp = null; 
GC.Collect(); 
GC.WaitForPendingFinalizers();

SpreadsheetGear for .NET will open only the workbooks you want it to open and in most cases runs much faster than using the Excel COM Interop APIs from .NET.

You can see samples here and download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM