This probably isn't the "right" way to do it, but for the same result in an ASP.NET Web API, the following worked for me:
public class WorkbookController : ApiController
{
public HttpResponseMessage Get()
{
// Create the workbook
var workbook = new XLWorkbook();
workbook.Worksheets.Add("Sample").Cell(1, 1).SetValue("Hello World");
// Prepare the response
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var memoryStream = new MemoryStream(); // If I put this in a 'using' construct, I never get the response back in a browser.
workbook.SaveAs(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin); // Seem to have to manually rewind stream before applying it to the content.
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "HelloWorld.xlsx" };
return response;
}
}
↧