I have the following piece of code to format the excel files that I get and save them as modified.xlsx
public void FormatFile()
{
FileName = Convert.ToString("test.xlsx");
SourceFileLocation = ("C:\Test");
SourceFileName = Path.Combine(SourceFileLocation, FileName);
saveLoc = Path.Combine(SourceFileLocation, "ModifiedExcel.xlsx");
var excel = new Excel.Application();
var workbook = excel.Workbooks.Open(SourceFileName);
//var sheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; // 1 is the first item, this is NOT a zero-based collection
try
{
foreach (Excel.Worksheet tempSheet in workbook.Worksheets)
{
if (((Excel.Worksheet)(tempSheet)).Name.Contains("Sheet1"))
{
if (File.Exists(saveLoc))
{
File.Delete(saveLoc);
}
tempSheet.Select();
workbook.SaveAs(saveLoc);
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(tempSheet);
}
workbook.Save();
workbook.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
}
catch(Exception)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
}
I release the excel objects but when I check my task manager I can still see excel processes running. If i have run this code multiple time, that many processes are created. Am I not releasing the excel objects correctly?