我有以下代码来格式化我得到的excel文件并将它们保存为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);
}
我发布了excel对象但是当我检查我的任务管理器时,我仍然可以看到excel进程正在运行。如果我多次运行此代码,则会创建许多进程。我没有正确发布excel对象吗?