title: How to export a DataTable variable to EXCEL and download the excel
body: <p>I'm trying to use NPOI like this:</p>
  
  <pre><code>private Stream RenderDataTableToExcel(DataTable SourceTable)
  {
      XSSFWorkbook workbook = null;
      MemoryStream ms = null;
      ISheet sheet = null;
      XSSFRow headerRow = null;
      try
      {
          workbook = new XSSFWorkbook();
          ms = new MemoryStream();
          sheet = workbook.CreateSheet();
          headerRow = (XSSFRow)sheet.CreateRow(0);
          foreach(DataColumn column in SourceTable.Columns)
              headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
          int rowIndex = 1;
          foreach(DataRow row in SourceTable.Rows)
          {
              XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
              foreach(DataColumn column in SourceTable.Columns)
                  dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
              ++rowIndex;
          }
          for (int i = 0; i &lt;= SourceTable.Columns.Count; ++i)
              sheet.AutoSizeColumn(i);
          workbook.Write(ms);
          ms.Flush();
      }
      catch (Exception ex)
      {
          return null;
      }
      finally
      {
          ms.Close();
          sheet = null;
          headerRow = null;
          workbook = null;
      }
      return ms;
  }
  private void DownloadExcel(DataTable dt, string reportName)
  {
      Stream s = RenderDataTableToExcel(dt);
      if (s != null)
      {
          MemoryStream ms = s as MemoryStream;
          Response.AddHeader("Content-Disposition", string.Format("attachment;filename=" + HttpUtility.UrlEncode(reportName) + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
          Response.ContentType = "application/vnd.ms-excel";
          Response.AddHeader("Content-Length", ms.ToArray().Length.ToString());
          Response.BinaryWrite(ms.ToArray());
          Response.Flush();
          ms.Close();
          ms.Dispose();
      }
      else
          Response.Write("Error!Connot Download");
  }
  </code></pre>
  
  <p>I've got binary stream instead of a ms-excel file.</p>
  
  <p>PS: I really want to know how to generate a file for download, that is, why your code works, the browser generates the file or the server?</p>