Reputation: 75
I'm writing a program where you can enter stuff into an excel via a button. When the button is pressed the Application is started it interacts with the spreadsheet.
But when it's finished interacting the process should be closed completely but it hangs in the Task Manager.
I've tried numerous solutions to close it but it won't.
Here is my code
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");
}
Upvotes: 1
Views: 521
Reputation: 75
Found the Solution. If you get your Range by
Range r = sheet.Cells[1,1];
Marshal.FinalReleaseComObject(r);
r = null;
Cells[1,1] creates an own COM object
Rang r1 = sheet.Cells;
Range r = r1[1,1];
Marshal.FinalReleaseComObject(r1);
r1 = null;
Marshal.FinalReleaseComObject(r1);
r1 = null;
by doing that it worked for me
Upvotes: 1