Hello,
Requirement is user will upload an excel file with students names and other data. After uploading, on same click event user should get an excel file stating row by row status whether student data created successfully or any error message.
On upload Click I call below action and post Excel and do all stuff validations in MVC action
function uploadFile(fileType, fileUpload) {
if (window.FormData !== undefined) {
var files = fileUpload.files;
var fileData = new FormData();
fileData.append(files[0].name, files[0]);
$.ajax({
url: '/Admin/UploadNewStudents',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
},
error: function (xhr) {
}
});
} else {
alert("FormData is not supported.");
}
}
[HttpPost]
public ActionResult UploadNewStudent()
{
try
{
HttpFileCollectionBase file = Request.Files;
string Message = StudentExcel.ValidateExcel(Request);
if (!string.IsNullOrEmpty(Message))
return Json(Message, JsonRequestBehavior.AllowGet);
else
{
HttpPostedFileBase pfile = Request.Files[0];
DataSet ds = StudentExcel.GetExcelData(pfile);
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
ws.Cells["A1"].LoadFromDataTable(ds.Tables[0], true);
Byte[] fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=DataTable.xlsx");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
Response.BinaryWrite(fileBytes);
Response.End();
}
}
}
catch (Exception ex)
{
}
return View();
}
I get desired Datatable in below code and setting into EPplus package and trying to download but Excel is not downloading. I don't want to save excel in server.
DataSet ds = StudentExcel.ValidateExcelData(pfile);
What I have tried:
Googling,
I think since action method is post I am not able to download excel. New to MVC, any help will be appreciated