In my ASP.NET MVC web application, I have used an action to give the user to select the excel file that he wants to upload. Then he submits it and uploaded it to the database.
This works when I run the application from Visual Studio. I have tried in the debug mode.
But when I apply this to the live version, It get an error. User Cannot Upload the excel to the application.
Does any one know the reason why this happens?
This is my controller code
public ActionResult ImportKPIDetails(HttpPostedFileBase excelFile) {
if (excelFile.ContentLength == 0 || excelFile == null) {
ViewBag.Error = "Please select the excel file";
return View("KPIDetails");
} else {
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx")) {
string path = Server.MapPath("~/ExcelFile/" + 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;
List < KPIUploadVM > xcel = new List < KPIUploadVM > ();
for (int i = 2; i <= range.Rows.Count; i++) {
try {
KPIUploadVM kpi = new KPIUploadVM();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
kpi.EmpId = EmpId;
kpi.KPI = ((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 2]).Text;
kpi.Year = int.Parse(((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 3]).Text);
KPIUploadVM Udata = new KPIUploadVM();
Udata.EmpId = kpi.EmpId;
Udata.KPI = kpi.KPI;
Udata.Year = kpi.Year;
xcel.Add(Udata);
} catch (Exception) {
workbook.Close(true, Missing.Value, Missing.Value);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
application.Quit();
ViewBag.Error = "Error in " + i + " record";
return View("KPIDetails");
}
}
if (xcel != null) {
try {
foreach(var item in xcel) {
int empID = item.EmpId;
string Kpi = item.KPI;
int year = item.Year;
MainKPI e = new MainKPI();
e.EmpId = empID;
e.KPI = Kpi;
e.Year = year;
e.Status = true;
e.CreatedDate = DateTime.Now;
dbs.MainKPI.Add(e);
dbs.SaveChanges();
}
} catch (Exception ex) {
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("KPIDetails", xcel);
} else {
}
return View("KPIDetails");
} else {
ViewBag.Error = "Selected excel file not supported";
return View("KPIDetails");
}
}
}