Titles Index

ID Title
1 Amazing Fantasy
2 Captain America
3 Conan The Barbarian
4 Daredevil
5 Defenders
6 Detective
7 Doctor Strange
8 Fantastice Four
9 Flash
10 Ghosst Rider
11 Giant Size X-Men
12 Green Lantern
13 Hulk
14 SgtFury
15 Silver Surfer
16 Strange Tales
17 Superman
18 Tales Of Suspense
19 Tales To Astonish
20 X-Men
Controller Methods:
  public ActionResult TitlesList()
  {
    return View(db.Titles.ToList());
  }

  public void ExportToExcel()
  {
    string Filename = "Titles.xls";
    string FolderPath = HttpContext.Server.MapPath("/ExcelFiles/");
    string FilePath = System.IO.Path.Combine(FolderPath, Filename);

    //Step-1: Check if file name exists in server then remove from server.
      if (System.IO.File.Exists(FilePath))
      {
        System.IO.File.Delete(FilePath);
      }

    //Step-2: Get Html Data & Converted to String
      List titlesList = db.Titles.OrderBy(d => d.TitleID).ToList();
      string HtmlResult = RenderRazorViewToString("TitlesList", titlesList);
    
    //Step-3: Html Result store in Byte[] array
      byte[] ExcelBytes = System.Text.Encoding.ASCII.GetBytes(HtmlResult);
    
    //Step-4: byte[] array converted to file Stream and save in Server
      using (Stream file = System.IO.File.OpenWrite(FilePath))
      {
        file.Write(ExcelBytes, 0, ExcelBytes.Length);
      }
    
    //Step-5: Download Excel file
      Response.ContentType = "application/vnd.ms-excel";
      Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(Filename));
      Response.WriteFile(FilePath);
      Response.End();
      Response.Flush();
}

//end of Controller Methods

Views
TitlesIndex.cshtml
@model IEnumerable<MvcBootstrap.Models.Titles>
@{
  ViewBag.Title = "Export to Excel  Index";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<style type="text/css">
  td {
    padding-right: 20px;
  }

  .border2pxSolidBlack {
    border: 2px solid black;
    font-weight: bold;
    font-size: large;
    padding: 4px;
  }

  .fontLargeBold {
    font-size: large;
    font-weight: bold;
  }

  .fontXLargeBoldBlack {
    font-size: x-large;
    font-weight: bold;
    color: black;
  }

 
  .marginTop20 {
    margin-top: 20px;
  }
</style>

<center>
  <h2>Titles Index</h2>

  <div class="row col-sm-12">
    <input type="button" id="btnDownload" class="btn mybtn-info" value="Export Titles to Excel File"
           onclick="generateToExcel_Click();" />
  </div>
</center>

<div class="row col-sm-12 well border2pxSolidBlack well marginTop20">
<center>
  <div class="row col-sm-12 marginTop20">
    <table>
      <tr>
        <th>
          ID
        </th>
        <th>
          Title
        </th>
      </tr>

      @foreach (var item in Model)
      {
        <tr>
          <td>
            @Html.DisplayFor(modelItem => item.TitleID)
          </td>
          <td>
            @Html.DisplayFor(modelItem => item.Title)
          </td>
        </tr>
      }

    </table>
  </div>
</center>

<script type="text/javascript">
  function generateToExcel_Click() {
    $("#lblErrMsg").html('Titles downloaded').css('color', 'blue');
    $("#btnDownload").css('color', 'white');
    window.location.href = 'ExportToExcel/';
  }
</script>
//end of TitlesIndex,cshtml

TitlesList.cshtml
@model IEnumerable<MvcBootstrap.Models.Titles>
<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Title
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.TitleID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
    </tr>
}

</table>
//end of TitlesList.cshtml
//end of Views