0
我有一段代碼打開一個Excel應用程序轉儲一個範圍,然後嘗試關閉它。c#Interop Excel關閉實例
無論我做什麼,嘗試成爲操作單詞我無法獲得關閉的excel實例 - 我遵循1點,而不是2點規則,據我所知,任何人都可以幫助我找到丟失的東西。
Excel.Application excelApp = new Excel.Application();
Excel.Workbooks wbks = excelApp.Workbooks;
Excel.Workbook currentWorkbook = wbks.Add();
Excel.Worksheet newWks = new Excel.Worksheet();
try
{
newWks = currentWorkbook.Sheets["Sheet2"];
newWks.Delete();
newWks = currentWorkbook.Sheets["Sheet3"];
newWks.Delete();
newWks=currentWorkbook.Sheets["Sheet1"];
for (int col = 0; col < dt.Columns.Count; col++)
{
newWks.Cells[1, col + 1] = dt.Columns[col].ColumnName;
}
string[,] arr = new string[dt.Rows.Count, dt.Columns.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[i, j] = dt.Rows[i][j].ToString();
}
}
Excel.Range startCell = newWks.Cells[2, 1];
Excel.Range endCell = newWks.Cells[dt.Rows.Count + 1, dt.Columns.Count];
Excel.Range writeRange = newWks.Range[startCell, endCell];
writeRange.Value2 = arr;
Excel.Application cwa = currentWorkbook.Application;
cwa.DisplayAlerts = false;
Global.CheckDirectory(path);
currentWorkbook.SaveAs(path + @"//filepath", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, Missing.Value,
Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
cwa.Quit();
Marshal.ReleaseComObject(cwa);
Marshal.ReleaseComObject(startCell);
Marshal.ReleaseComObject(endCell);
Marshal.ReleaseComObject(writeRange);
}
catch (Exception ex)
{
//err handler
}
finally
{
wbks.Close();
excelApp.Quit();
Marshal.ReleaseComObject(newWks);
Marshal.ReleaseComObject(currentWorkbook);
Marshal.ReleaseComObject(wbks);
Marshal.ReleaseComObject(excelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
見[這裏](https://stackoverflow.com/questions/158706/how-do-i-properly-clean-up-excel-interop-objects)和[這裏](https://開頭stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685)。 – Equalsk
您已經擁有了Excel應用程序excelApp的1個實例。是否有任何理由設置Excel.Application cwa = currentWorkbook.Application;?只需excelApp.Quit();最後應該做的工作,並保持excelApp:你可以做excelApp.DisplayAlerts = false; DisplayAlerts屬於Excel應用程序而不是工作簿。 –