在C#中的ComObject发布之后如何修复excel?
在执行了下面的代码之后:
Microsoft.Office.Interop.Excel.Application oXL; oXL = new Microsoft.Office.Interop.Excel.Application(); oXL.Visible = false; oXL.IgnoreRemoteRequests = true; oXL.DisplayAlerts = false; Workbook oWB; oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); Sheets excelSheets = oWB.Worksheets; string currentSheet = "PC_HW_Info"; Worksheet excelWorksheet = excelSheets.get_Item(currentSheet); string columnRange; int rowsNumber = 2; Range PC_User; PC_User = excelWorksheet.get_Range("A2", "A2"); while ((PC_User.Value2) != null) { ++rowsNumber; columnRange = "A" + rowsNumber; PC_User = excelWorksheet.get_Range(columnRange, columnRange); } PC_User.Value2 = "aaaa"; oXL.UserControl = false; oWB.SaveAs("valid path to my file", XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); oWB.Close(); oXL.Quit(); Marshal.ReleaseComObject(oXL); Marshal.ReleaseComObject(oWB); Marshal.ReleaseComObject(excelSheets); Marshal.ReleaseComObject(excelWorksheet);
我的Excel是以某种方式损坏,即使重新启动它不会回到他的初始工作状态。 现在我无法直接打开工作表,我不得不使用打开 – >浏览来访问工作表。
在第一次运行时,当我打开我操作的原始文档的“恢复”版本的工作表似乎已经恢复,我已经恢复,但从那时起,我不能像以前那样使用Excel。
请任何想法? 我在ReleaseComObject上做错了什么? 我应该如何closuresexcel应用程序?
LE:如果我评论所有closures并释放对象的最后一行,它就能正常工作。
Microsoft.Office.Interop.Excel.Application oXL; oXL = new Microsoft.Office.Interop.Excel.Application(); oXL.Visible = false; oXL.IgnoreRemoteRequests = true; oXL.DisplayAlerts = false; Workbook oWB; Workbooks wbs = oXL.Workbooks; //Never use two dots, since the middle one needs free as well oWB = wbs.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); Marshal.ReleaseComObject(wbs); Sheets excelSheets = oWB.Worksheets; string currentSheet = "PC_HW_Info"; Worksheet excelWorksheet = excelSheets.get_Item(currentSheet); string columnRange; int rowsNumber = 2; Range PC_User; PC_User = excelWorksheet.get_Range("A2", "A2"); // Need to free while ((PC_User.Value2) != null) { ++rowsNumber; columnRange = "A" + rowsNumber; Marshal.ReleaseComObject(PC_User); PC_User = excelWorksheet.get_Range(columnRange, columnRange); } PC_User.Value2 = "aaaa"; Marshal.ReleaseComObject(PC_User); oXL.UserControl = false; oWB.SaveAs("valid path to my file", XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); oWB.Close(); Marshal.ReleaseComObject(excelWorksheet); Marshal.ReleaseComObject(excelSheets); Marshal.ReleaseComObject(oWB); oXL.Quit(); Marshal.ReleaseComObject(oXL);
你忘了释放范围和工作簿对象。 你也有免费的订购错误(虽然我不认为它会有影响,只是为了安全)
通过不释放所有的对象,你将在后台留下一个鬼怪的Excel过程。 尝试杀死那些人,看看它是否解决了这个问题