C# REST API to download excel sheet by EPPlus. Working code. From data
table.
[HttpGet]
public string
TestExcel()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Step 3: here we add 5 rows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
using (ExcelPackage p = new ExcelPackage())
{
ExcelWorksheet ws1 = p.Workbook.Worksheets.Add("RSL Master");
ws1.Cells["A1"].LoadFromDataTable(table,
true,
OfficeOpenXml.Table.TableStyles.None);
Byte[] bin =
p.GetAsByteArray();
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;
filename=RSL_Master.xlsx");
System.Web.HttpContext.Current.Response.ContentType
= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Web.HttpContext.Current.Response.BinaryWrite(bin);
System.Web.HttpContext.Current.Response.End();
}
return "success";
}