我在我的网站项目中使用C#中的Excel互操作来解析excel文件并将其转换为文本文件。示例代码如下。我是否需要在foreach循环中释放excel工作表对象?
Excel.Application excel=new Excel.Application();
Excel.Workbooks wbs=excel.Workbooks;
Excel.Workbook wb=wbs.Open(…);
Try
{
…
Foreach(Excel.Worksheet sheet in wb.Sheets)
{
…
Marshal.RealseComObject(sheet);
sheet=null; //compiler error
}
…
}
Catch()
{
}
Finally
{
wb.Close(false, missing, missing);
while (Marshal.ReleaseComObject(wb)!=0)
{
}
wb=null;
while (Marshal.ReleaseComObject(wbs)!=0)
{
}
wbs=null;
excel.Quit();
while (Marshal.ReleaseComObject(excel)!=0)
{
}
excel=null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
我的问题是我需要释放foreach循环中的工作表对象吗?我看到了一些关于使用excel工作表进行编程的示例代码,但都没有。如果我确实需要放弃对象,那么在我的foreach循环中,我无法将表单设置为null,是否意味着我不应该使用foreach?
我相信我已经在[此帖]中回答了你(http://stackoverflow.com/questions/19713082/what-is-the-best-practise-to-relase-excel-interop-objects-in- C/19713398?noredirect = 1个#comment29396895_19713398)。 – Brian