简体   繁体   English

杀死 Excel 进程 c#

[英]Killing the Excel Process c#

In my web application, I have added an excel upload section.在我的 web 应用程序中,我添加了一个 excel 上传部分。

Here When the user selects the excel file and clicked the upload button the below code is running.这里当用户选择 excel 文件并单击上传按钮时,下面的代码正在运行。

If there was an error in upload it returns to the main page again and, when the user tried to upload the excel file again, it returns an error.如果上传出错,它会再次返回主页,当用户再次尝试上传 excel 文件时,它会返回错误。

So I checked this by opening the task manager, and then I saw that the EXCEL process is running in the background.于是我打开任务管理器查看了这个,然后看到后台运行的是EXCEL进程。 When I end the process of the excel file from there, then I can upload the excel file again.当我从那里结束 excel 文件的过程时,我可以再次上传 excel 文件。

So is there any way if the excel process is running kill that process and run the code without any error from the excel process.如果 excel 进程正在运行,那么有什么办法可以杀死该进程并运行代码,而 excel 进程没有任何错误。 ? ?

This is the existing code.这是现有的代码。

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;
}

Killing a process is like using a sledgehammer to drive in a panel pin.杀死一个进程就像用大锤敲入一个面板引脚。 It'll work but what damage will it do in the process?它会起作用,但它会在这个过程中造成什么损害?

when using iterop you need to use Try-Catch and Using使用 iterop 时,您需要使用 Try-Catch 并使用

using xlapp = new Microsoft.Office.Interop.Excel.Application()
{
    Try{
     [The rest of your code here]
     xlapp.cose()
    catch{
     xlapp.Dispose()
    }

} }

This will make sure that the instance of excel that you created in code is disposed of should there be an error nd will be correctly closed when you are done with it.这将确保您在代码中创建的 excel 实例在出现错误时被处置,并且在您完成后将被正确关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM