C# create/modify/read .xlsx files

With EPPlus it’s not required to create file, you can do all with streams, here is an example of ASP.NET ashx handler that will export datatable into excel file and serve it back to the client :

  public class GetExcel : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      var dt = DBServer.GetDataTable("select * from table");
      var ms = GetExcel.DataTableToExcelXlsx(dt, "Sheet1");
      ms.WriteTo(context.Response.OutputStream);
      context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      context.Response.AddHeader("Content-Disposition", "attachment;filename=EasyEditCmsGridData.xlsx");
      context.Response.StatusCode = 200;
      context.Response.End();   
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }

    public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
    {
      var result = new MemoryStream();
      var pack = new ExcelPackage();
      var ws = pack.Workbook.Worksheets.Add(sheetName);

      int col = 1;
      int row = 1;
      foreach (DataRow rw in table.Rows)
      {
        foreach (DataColumn cl in table.Columns)
        {
          if (rw[cl.ColumnName] != DBNull.Value)
            ws.Cells[row, col].Value = rw[cl.ColumnName].ToString();
          col++;
        }
        row++;
        col = 1;
      }
      pack.SaveAs(result);
      return result;
    }
  }

Leave a Comment