关闭excel后如何清理excel互操作对象
当我运行以下代码时,Excel对象仍保留在任务管理器中。
Excel.Application appExl = new Excel.Application();
Excel.Workbook工作簿= null;
Excel.Worksheet nwSheet = null;
Excel.Range last = null,range = null;
//打开Excel
workbook = appExl.Workbooks.Open(@ txtBrowse.Text,Missing.Value,false,Missing。 Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
nwSheet =(Excel.Worksheet)workbook.Sheets.get_Item(1);
last = nwSheet.Cells .SpecialCells(Excel.XlCellType.xlCellTypeLastCell,Type.Missing);
range = nwSheet.get_Range(A1,last);
int last UsedRow = last.Row;
nwSheet.Cells [1,1] .Value2 =test;
workbook.Save();
When I am running following code Excel object remains in task manager.
Excel.Application appExl = new Excel.Application();
Excel.Workbook workbook = null;
Excel.Worksheet nwSheet = null;
Excel.Range last = null, range = null;
//Open Excel
workbook = appExl.Workbooks.Open(@txtBrowse.Text, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
nwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
last = nwSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
range = nwSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
nwSheet.Cells[1, 1].Value2 = "test";
workbook.Save();
if (last != null)
Marshal.FinalReleaseComObject(last);
last = null;
if (range != null)
Marshal.FinalReleaseComObject(range);
range = null;
if (nwSheet != null)
Marshal.FinalReleaseComObject(nwSheet);
nwSheet = null;
if (workbook != null)
{
workbook.Close(true, Missing.Value, Missing.Value);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
}
workbook = null;
if (appExl != null)
{
((Excel._Application)appExl).Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExl);
}
appExl = null;
GC.Collect();
我也试过这个也是
workbook.Close();
Marshal.ReleaseComObject(工作簿);
appExl.Quit();
Marshal.ReleaseComObject(appExl );
workbook = null;
appExl = null;
GC.Collect();
GC.Collect();
I have tried this one also
workbook.Close();
Marshal.ReleaseComObject(workbook);
appExl.Quit();
Marshal.ReleaseComObject(appExl);
workbook=null;
appExl=null;
GC.Collect();
获取正在运行的进程列表并终止正在使用的进程。
get the list of running processes and kill the one you are using.