参考:https://dev59.com/cGQm5IYBdhLWcg3wwxLF#17367570
避免使用双点调用表达式,例如:
var workbook = excel.Workbooks.Open()
...因为这样你不仅会为工作簿创建RCW对象,还会为Workbooks创建RCW对象,而且你也需要释放它们(如果没有维护对象的引用,则无法释放)。
这对我解决了问题。你的代码将变成:
public Excel.Application excelApp = new Excel.Application();
public Excel.Workbooks workbooks;
public Excel.Workbook excelBook;
workbooks = excelApp.Workbooks;
excelBook = workbooks.Add(@"C:/pape.xltx");
...
Excel.Sheets sheets = excelBook.Worksheets;
Excel.Worksheet excelSheet = (Worksheet)(sheets[1]);
excelSheet.DisplayRightToLeft = true;
Range rng;
rng = excelSheet.get_Range("C2");
rng.Value2 = txtName.Text;
然后释放所有这些对象:
System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
excelBook .Save();
excelBook .Close(true);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
我将这个代码块放在 try {} finally {}
中,以确保即使出现问题(可能会发生什么问题?),也能释放所有资源,例如:
我将其包装在try {} finally {}
中,以确保即使出现错误(有什么是可能会出错的呢?),一切都能得到释放,例如:
(Two possible translations with slightly different phrasing, but both convey the same meaning.)
public Excel.Application excelApp = null;
public Excel.Workbooks workbooks = null;
...
try
{
excelApp = new Excel.Application();
workbooks = excelApp.Workbooks;
...
}
finally
{
...
if (workbooks != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
}