我正在用C#編寫這個特定的代碼來寫入Excel文件。Excel不會退出C#
public partial class WriteExcelForm : Form
{
public WriteExcelForm()
{
InitializeComponent();
}
private void writeExcelButton_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not installed!!!");
return;
}
Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
Excel.Workbook xlWorkBook = xlWorkBooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = xlWorkBook.ActiveSheet;
xlWorkSheet.Name = "sample";
Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
range1.Value = "dhiraj";
Excel.Range range2 = xlWorkSheet.Range["A2"];
range2.Value = "dhiraj";
xlWorkBook.SaveAs("C:\\output.xlsx");
//Properly closing the excel app
GC.Collect();
GC.WaitForPendingFinalizers();
xlWorkBook.Close(false, Type.Missing, Type.Missing);
xlApp.Quit();
Marshal.FinalReleaseComObject(range1);
Marshal.FinalReleaseComObject(range2);
Marshal.FinalReleaseComObject(xlWorkSheet);
Marshal.FinalReleaseComObject(xlWorkBook);
Marshal.FinalReleaseComObject(xlWorkBooks);
Marshal.FinalReleaseComObject(xlApp);
}
}
如果我運行這段代碼,excel.exe不會退出,但會一直掛在後臺。
但是,如果我註釋掉這一行
Excel.Range range1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
range1.Value = "dhiraj";
的EXCEL.EXE優雅退出。
我在這裏錯過了什麼?
編輯: 我已經解決了我的問題。發表我的發現作爲答案。
P.S:不知道我爲什麼被拒絕投票,在發佈這個問題之前,我做了很多研究。
@ YowE3K:你是說沒有明確的類型轉換?我曾嘗試過,但最終得到的結果相同。 –
檢查此鏈接:http://www.siddharthrout.com/2012/08/06/vb-net-two-dot-rule-when-working-with-office-applications-2/ - 並消除雙點。還建議您避免使用括號符號來進行類型轉換。 –
看到這個:https://stackoverflow.com/questions/29067714/vsto-manipulating-com-objects-one-dot-good-two-dots-bad - 對於一個櫃檯點。 –