我有一個函數來讀取Excel,然後工作簿和工作表。 但Excel線程永遠不會完成。我嘗試了我在這裏找到的每個解決方案,但都沒有奏效。c#Excel線程沒有完成(FinalReleaseComObject)
Excel任務管理器上的線程堆棧,以及由於Excel停止工作而導致應用程序崩潰。
public static object[,] ReadFile(string filepath, string sheetname)
{
Application xlApp = null;
Workbooks wks = null;
Workbook wb = null;
object[,] values = null;
try
{
xlApp = new ApplicationClass();
wks = xlApp.Workbooks;
wb = wks.Open(filepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Worksheet sh = (Worksheet)wb.Worksheets.get_Item(sheetname);
values = sh.UsedRange.Value2 as object[,];
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sh);
sh = null;
}
catch (Exception ex)
{
throw new Exception(string.Format("Sheet \"{0}\" does not exist in the Excel file", sheetname));
}
finally
{
if (wb != null)
{
wb.Close(false);
Marshal.FinalReleaseComObject(wb);
wb = null;
}
if (wks != null)
{
wks.Close();
Marshal.FinalReleaseComObject(wks);
wks = null;
}
if (xlApp != null)
{
// Close Excel.
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
xlApp = null;
}
}
return values;
}
也許我不按照正確的順序做事情,或者我理解錯了COM對象問題。
你的應用崩潰在哪一行? – Gusman
我必須閱讀很多Excel文件。因此,代碼每次在「xlApp = new ApplicationClass();」上啓動Excel。我認爲「xlApp.Quit(); Marshal.FinalReleaseComObject(xlApp); xlApp = null;」足以媲美Excel。但Excel永遠不會關閉。因此,應用程序崩潰是因爲在某個時刻,我有近20個EXCEL.EXE進程在後臺運行。 – Delta
FinalReleaseComObject應該不是必需的。您正在使用.net包裝爲Excel。如果你刪除FinalReleaseComObject會發生什麼? – Uwe