【发布时间】:2020-06-08 22:00:12
【问题描述】:
我正在编写一个程序,您可以在其中通过按钮将内容输入到 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");
}
【问题讨论】:
-
从 WB.Close() 中删除零也删除 wbs.Close();这是不需要的,如果在 WB.Close() 之后会出错,因为工作簿不存在。
-
这对您有帮助吗? link
-
@jdweng 我没有收到任何错误,删除 0 对问题没有影响
-
@YosefBernal 已经尝试过了。而且我不想通过杀死进程来使用大锤方法
-
你发布了所有的excel代码吗?有些方法会创建新的工作簿,您可能会创建多个工作簿。工作簿可能正在关闭,但应用程序 oxl 没有关闭。或者你可能会遇到异常。您解决问题的一些尝试可能会导致异常并使问题变得更糟。最好把所有不需要的代码都注释掉,从头开始。