杀死 Excel 进程 c#

Killing the Excel Process c#

在我的网络应用程序中,我添加了一个 excel 上传部分。

此处 当用户选择 excel 文件并单击上传按钮时,下面的代码是 运行ning.

如果再次上传 returns 到主页时出错,并且当用户尝试再次上传 excel 文件时,returns 出错。

所以我通过打开任务管理器检查了这一点,然后我看到 EXCEL 进程正在后台 运行ning。当我从那里结束 excel 文件的进程时,我可以再次上传 excel 文件。

如果 excel 进程正在 运行 终止该进程并且 运行 代码没有来自 excel 进程的任何错误,那么有什么办法吗? ?

这是现有代码。

if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx")) 
{
  string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
  KillSpecificExcelFileProcess(excelFile.FileName);
  if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
  excelFile.SaveAs(path);
  ExcelPath = Server.MapPath("~/ExcelFile/") + path;
  Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
  Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
  Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
  Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
}

杀死一个进程就像用大锤敲面板的针一样。它会起作用,但在此过程中会造成什么损害? 使用 iterop 时需要使用 Try-Catch-Finally

try
{
    app = new Excel.Application();
    books = app.Workbooks;
    book = books.Add();
    sheets = book.Sheets;
    sheet = sheets.Add();
    range = sheet.Range["A1"];
    range.Value = "Lorem Ipsum";
    book.SaveAs(@"C:\Temp\ExcelBook" + 
   DateTime.Now.Millisecond + ".xlsx");
    book.Close();
    app.Quit();
}
finally
{
    if (range != null) Marshal.ReleaseComObject(range);
    if (sheet != null) Marshal.ReleaseComObject(sheet);
    if (sheets != null) Marshal.ReleaseComObject(sheets);
    if (book != null) Marshal.ReleaseComObject(book);
    if (books != null) Marshal.ReleaseComObject(books);
    if (app != null) Marshal.ReleaseComObject(app);
}

这将确保您在代码中创建的 excel 实例在出现错误时被处理掉,并且在您完成后将被正确关闭。