I am creating an excel file with EPPlus library and I want to download it to client.
Here is an example of EPPlus
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Sample1");
ws.Cells["A1"].Value = "Sample 1";
ws.Cells["A1"].Style.Font.Bold = true;
var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
shape.SetPosition(50, 200);
shape.SetSize(200, 100);
shape.Text = "Sample 1 saves to the Response.OutputStream";
pck.SaveAs(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Sample1.xlsx");
This code creates xls file and allows to download it to client from an aspx page. I have tried to request xls file with 'HttpWebRequest' class from my.aspx page but I get an error that says 'Operation is not valid due to the current state of the object'.
How can I download this xls file from server to client?
Probably better to do a BinaryWrite
. Here is how I do it:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=myfilename.xlsx");
HttpContext.Current.Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
HttpContext.Current.Response.BinaryWrite(pck.GetAsByteArray());
HttpContext.Current.Response.Flush();