title: How to download excel (.xlsx) via ajax in .net core 2.0
body: <p>I am trying to download an excel file with large data set. On server side I am using EPPlus library to generate excel. I then pass the stream obj to client side. Client side code download the excel file using that stream obj.<br>
  <strong>When I open the downloaded file I get corrupt file error message. Where I am going wrong?</strong></p>
  
  <blockquote>
    <p>Server side code (C#)</p>
  </blockquote>
  
  <pre><code>public async Task&lt;IActionResult&gt; DownloadExcel(Model postData)
  {
      string apiUrl = "Api/URL/Get";
      apiUrl += "?Status=" + postData.Status +
                "&amp;Gender=" + postData.Gender +
                "&amp;CurrentAge=" + postData.CurrentAge;
  
      var result = await CallAPI.GetListFromApiAsync&lt;ResultModel&gt;(apiUrl);
  
      var stream = new MemoryStream();
      using (ExcelPackage excel = new ExcelPackage(stream))
      {
          var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
  
          //  Column
          workSheet.Cells[1, 1].Value = "Column 1";
          workSheet.Cells[1, 2].Value = "Column 2";
          .
          .
          .
          workSheet.Cells[1, 19].Value = "Column 19";
  
          // Row
          int recordIndex = 2;
          foreach (var d in result)
          {
              workSheet.Cells[recordIndex, 1].Value = d.data1;
              workSheet.Cells[recordIndex, 2].Value = d.data2;
              .
              .
              .
              workSheet.Cells[recordIndex, 19].Value = d.data4;
              recordIndex++;
          }
          for (int i = 1; i &lt; 20; i++)
          {
              workSheet.Column(i).AutoFit();
          }
  
          string fileName = @"download.xlsx";
          string fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
          stream.Position = 0;
          return File(stream, fileType, fileName);
      }
  }
  </code></pre>
  
  <blockquote>
    <p>Client side ajax call</p>
  </blockquote>
  
  <pre><code>$.ajax({
      url: "/SomeURL/DownloadExcel",
      type: "POST",
      data: form.serialize(),
      success: function (result) {
          var binaryData = [];
          binaryData.push(result);
          var blob = new Blob([binaryData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'download.xlsx';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
      }
  });
  </code></pre>