Rukshar Khan

Rukshar Khan

  • NA
  • 33
  • 2.8k

Save data selected from dropdownlist to excel in MVC

Jul 4 2017 5:40 PM
I have created a view in MVC 5 that allows the end user to select the data from dropdownlist. Once the user has selected all the information, upon click i want those selected data to be shown in the excel in respective cell lets say countryname in A2. How can i go about doing this.
 
Controller Code 
public ActionResult Search()
{
var MarkViewModel = new MarkViewModel
{
Countries = _context.Countries.ToList(),
School = _context.Schools.ToList(),
};
return View("Search", MarkViewModel);
}
 
View

 
@model SIMS.ViewModels.MarkViewModel
@{
ViewBag.Title = "Search";
}
{
@Html.AntiForgeryToken()
<fieldset>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.CountryId, new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.DropDownListFor(m => m.CountryId, new SelectList(Model.Countries, "Id", "Name"), "Select Country", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.CountryId, "", new { @class = "text-danger" })
</div>
</div>
@Html.HiddenFor(m => m.Id)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
@Html.ActionLink("Cancel", "Index", "Mark", null, new { @class = "btn btn-default" })
<button type="submit" id="btnSave" class="btn btn-raised btn-primary">Mark</button>
</div>
</div>
 
Excel i have managed to download excel and set the ranges in the excel form. having issue with capturing data from MVC to excel.
 
Excel code
 
public ActionResult MarktoExcel()
{
MemoryStream ms = new MemoryStream();
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("test");
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=mark.xlsx");
Response.Charset = "";
worksheet.Cell(3, 1).Value = "Country:";
worksheet.Cell(3, 1).Style.Font.Bold = true;
worksheet.Range("B3:B4").Style.Border.RightBorder = XLBorderStyleValues.Thin;
worksheet.Range("A3:B3").Merge();
worksheet.Protect();
workbook.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();

Answers (2)