我正在创建可从数据库数据生成Excel文件的Windows窗体应用程序。在将数据库填充到文件中后,我打开它并执行一个宏,保存该文件然后关闭它(或者我认为我正在关闭它)。这些文件保存在我的硬盘上,但是当生成所有文件时,我必须能够生成一组新文件,因此我必须在生成新的硬盘之前从硬盘上删除所有旧文件。运行应用程序一次后,我尝试生成新的文件集,我得到一个错误,指出其中一个文件(第一批生成的最后一个文件)被另一个进程使用。创建并编辑后发布Excel文件
这里是我的代码:
public void RemoveRows_Macro(string fileName)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open(fileName);
//xlApp.Visible = true;
xlApp.DisplayAlerts = true;
//Run the macro
xlApp.Run("RemoveRows", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Save();
xlWorkBook.Close(false);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
Console.WriteLine("Error in releasing object :" + ex);
obj = null;
}
finally
{
GC.Collect();
}
}
我在做什么错误的,因为应用程序未释放的文件?
对不起,我输错了!即时尝试它。 – Lahib 2013-03-19 08:20:52
编辑我的答案 – TalentTuner 2013-03-19 08:22:02
它的工作。我很感激帮助。谢谢 – Lahib 2013-03-19 08:28:21