在我的 Web 應用程式中,我添加了一個 Excel 上傳部分。
這里當用戶選擇 excel 檔案并單擊上傳按鈕時,下面的代碼正在運行。
如果上傳出錯,它會再次回傳主頁面,當用戶再次嘗試上傳 excel 檔案時,它會回傳錯誤。
于是我打開任務管理器查看了這個,然后看到EXCEL行程在后臺運行。當我從那里結束 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;
}
uj5u.com熱心網友回復:
殺死一個行程就像用大錘敲入一個面板引腳。它會起作用,但它會在這個程序中造成什么損害?使用 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 實體在出現錯誤時被處置,并且在您完成后將正確關閉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421546.html
標籤:
