Goal:
Copy specific sheet from workbook and paste it into a brand new excel file. (Done)
Close the excel program properly, so the process does not appear in the Task Manager. (Not-Done) - Main Issue
Code:
public Excel.Application excelApp = null;
public Excel.Workbooks workbooks = null;
public Excel.Workbook target = null;
private void button1_Click(object sender, EventArgs e)
{
//Excel Application
excelApp = new Excel.Application();
//Excel Workbooks
workbooks = excelApp.Workbooks;
//Excel Workbook
target = workbooks.Add(@"C:\Users\LV98\Desktop\Test C#\test.xlsx");
//Excel all sheets from Workbook
Excel.Sheets sheets = target.Worksheets;
//Get specific sheet name
Excel.Worksheet workingSheet = (Excel.Worksheet)sheets.get_Item("Sheet2");
//New book
var newbook = excelApp.Workbooks.Add(1);
//Copy selected sheet to new book
workingSheet.Copy(newbook.Sheets[1]);
newbook.SaveAs(@"C:\Users\LV98\Desktop\Test C#\template.xlsx");
newbook.Close(0);
target.Close();
excelApp.Quit();
}
Details:
It works as it should. But the original file we copied the sheet from. The Excel process is still running.
This means the file is locked for editing.
What I have tried:
public Excel.Application excelApp = null;
public Excel.Workbooks workbooks = null;
public Excel.Workbook target = null;
private void button1_Click(object sender, EventArgs e)
{
//Excel Application
excelApp = new Excel.Application();
//Excel Workbooks
workbooks = excelApp.Workbooks;
//Excel Workbook
target = workbooks.Add(@"C:\Users\LV98\Desktop\Test C#\test.xlsx");
//Excel all sheets from Workbook
Excel.Sheets sheets = target.Worksheets;
//Get specific sheet name
Excel.Worksheet workingSheet = (Excel.Worksheet)sheets.get_Item("Sheet2");
//New book
var newbook = excelApp.Workbooks.Add(1);
//Copy selected sheet to new book
workingSheet.Copy(newbook.Sheets[1]);
newbook.SaveAs(@"C:\Users\LV98\Desktop\Test C#\template.xlsx");
newbook.Close(0);
target.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workingSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(newbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(target);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}
Details:
Got this from here :https://stackoverflow.com/a/28080347/12485722
This still does not work. Works exactly the same as the 1st code, and the EXCEL.exe process is still running.
Question:
Why is it still running as a process? And how can I fix this?