1

Having read many threads on here about not using double dots when referencing excel com objects, I decided to implement it.

It worked up until I came to doing in my loop.

Here is my loop. Note that it works if I comment this out:

        for (int i = 1; i < dgv.Columns.Count + 1; i++)
        {
            excelWorkbook.Cells[1, i] = dgv.Columns[i - 1].HeaderText;

            var cell = excelWorkbook.Cells[1, i];
            var fontSetter = cell.Font;
            fontSetter.Bold = true; //Bolds the header row

            // Garbage collecting
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(fontSetter);
            Marshal.FinalReleaseComObject(cell);
        }

Shouldn't my code dispose of them variables correctly?

Here is my full code:

[Code removed]

I am trying to follow the steps over at How do I properly clean up Excel interop objects? (the second answer)

Community
  • 1
  • 1
TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101

2 Answers2

1

It's not easy to get this right. But I'm surprised the following even compiles:

excelWorkbook.Cells[1, i] = dgv.Columns[i - 1].HeaderText; 
var cell = excelWorkbook.Cells[1, i]; 

Perhaps you meant:

excelWorkbook.Cells[1, i].Value = dgv.Columns[i - 1].HeaderText; 
var cell = excelWorkbook.Cells[1, i]; 

which should be replaced by:

var cell = excelWorkbook.Cells[1, i]; 
cell.Value = dgv.Columns[i - 1].HeaderText; 

I don't see the point in your GC.Collect and GC.WaitForPendingFinalizers calls, since you make them before cell and fontSetter go out of scope.

Finally the calls to Marshal.FinalReleaseComObject should probably be in a finally block, so that they will be executed even if an Exception is thrown.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • I tried doing that by puttng the full loop in a try and then using finally, but It wasen't able to find the variables. Maybe because they are declared in the loop? – TheGateKeeper Mar 31 '12 at 12:17
  • Yes, the try/finally would have to be inside the loop. Each time through the look, you reference a new cell and its font, and you have to release all of them. – Joe Mar 31 '12 at 15:45
0

I did it by following the method specified by nightcoder in How do I properly clean up Excel interop objects?.

You don't need to reference anything and has the least clutter of them all, it closes the process by its ID. Hope this helps someone who comes in looking.

Community
  • 1
  • 1
TheGateKeeper
  • 4,420
  • 19
  • 66
  • 101