C# Excel 进程不会关闭



我正在编写一个程序,您可以在其中通过按钮将内容输入到excel中。 按下按钮时,应用程序启动,它与电子表格交互。

但是当它完成交互时,进程应该完全关闭,但它在任务管理器中挂起。

我已经尝试了许多解决方案来关闭它,但它不会。

这是我的代码

using Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Runtime.InteropServices;
using Application = Microsoft.Office.Interop.Excel.Application;
.
.
.
.
Application oxl = null;
Workbooks wbs = null;
Workbook wb = null;
Worksheet ws = null;
Sheets wss = null;
Range r = null;
Range orange2 = null;
Range resultRange = null;

try {
oxl = new Application();
wbs = oxl.Workbooks;
wb = wbs.Open(Settings.Default.excelPath);
wss = wb.Worksheets;
ws = (Worksheet) wss[2];
r = ws.Range["A2:A924"];
foreach(string tofind in tofinds) {
resultRange = null;
string[] s = data[tofind];
resultRange = r.Find(
What: tofind,
LookIn: XlFindLookIn.xlValues,
LookAt: XlLookAt.xlPart,
SearchOrder: XlSearchOrder.xlByRows,
SearchDirection: XlSearchDirection.xlPrevious,
MatchCase: true);
if (resultRange != null) {
int i = resultRange.Row;
orange2 = ws.Cells[i, 2];
if (orange2.Value == null) {
orange2 = ws.Cells[i, 2];
//s[0]= -3.94e6
orange2.Value = s[0].Split((char)
'e')[0].Replace("-", "");
orange2.NumberFormat = "0.00";
}
} else {
//Log to Console
}

}
wb.Save();
} catch (IOException e) {
Console.WriteLine(e.Message);
} finally {
Marshal.FinalReleaseComObject(orange2);
Marshal.FinalReleaseComObject(r);
Marshal.FinalReleaseComObject(resultRange);
orange2 = null;
r = null;
resultRange = null;

foreach(Worksheet sheet in wss) {
Marshal.FinalReleaseComObject(sheet);
}
Marshal.FinalReleaseComObject(wss);
wss = null;
wb.Close(0);
wbs.Close();
foreach(Workbook workbook in wbs) {
Marshal.FinalReleaseComObject(workbook);
}
Marshal.FinalReleaseComObject(wb);
wb = null;
Marshal.FinalReleaseComObject(wbs);
wbs = null;
oxl.Application.Quit();
oxl.Quit();
Marshal.FinalReleaseComObject(oxl);
oxl = null;

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Final");
}

找到了解决方案。 如果您通过以下方式获得范围

Range r = sheet.Cells[1,1];
Marshal.FinalReleaseComObject(r);
r = null;

单元格[1,1] 创建自己的 COM 对象

Rang r1 = sheet.Cells;
Range r = r1[1,1];
Marshal.FinalReleaseComObject(r1);
r1 = null;
Marshal.FinalReleaseComObject(r1);
r1 = null;

通过这样做,它对我有用

最新更新