Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using VS 2012, .NET 4.5, Excel Interop 14

I'm reading in an Excel file and working though all the sheets to extract data from a number of them. I'm fairly certain I'm releasing all the memory correctly with the code below (source).

C#
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
 
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);


So my question is, in the code below, will the sheet created by the foreach loop properly release the memory?
C#
foreach (var oSheet in oWB.Sheets)
{
    ...next chunk of code
}


Or do I have to do it like this?
C#
for (int i = 1; i < oWB.Sheets.Count; i++)
{
    Excel._Worksheet oSheet = oWB.Sheets[i];
    ...next chunk of code    

    Marshal.ReleaseComObject(oSheet);
    oSheet = null;
}
Posted
Comments
PIEBALDconsult 3-Dec-14 13:40pm    
Dunno, but I recommend accessing Excel as if it's a database, using ADO.net, the ACE engine, and the OleDb provider.
Will Elliott 4-Dec-14 9:15am    
Could you point me to some reference material for that? I'm always game for exploring new options.

You are looping through the sheets. No need to release anything here. The sheets are already in memory and you are looping through them.

Al last, you just need to release the workbook and quit the application.
 
Share this answer
 
OK. The initial question wasn't clear enough...sorry. This might be answering my own question. Using a foreach loop, this seems to be the only way to access properties and data of the sheet.
C#
foreach (var oSheet in oWB.Sheets)
{
    Excel._Worksheet sheet = oSheet as Excel._Worksheet;
    if(sheet.Name.Contains( $TEST_VAL ) 
    {
        function1(sheet);
    }
    Marshal.ReleaseComObject(sheet);
    sheet = null;
}
 
Share this answer
 
Comments
PIEBALDconsult 4-Dec-14 9:47am    
Not polite to answer your own question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900