issue with returning HttpResponseMessage as excel file in WebAPI

匆匆过客 提交于 2019-12-02 05:16:31

Try this:

    [HttpGet]
    public HttpResponseMessage Export()
    {
        using (var wb = new XLWorkbook())
        using (MemoryStream ms = new MemoryStream())
        {
            wb.Worksheets.Add("sample").FirstCell().SetValue("some value");

            wb.SaveAs(ms);

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(ms.GetBuffer());
            result.Content.Headers.ContentLength = ms.Length;
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "sample.xlsx"
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            return result;
        }
    }

One issue I am seeing is that :

 var stream = new FileStream(path, FileMode.Open);

you are sending FileStream. Instead of this, you can try with byte [] :

byte[] excelData  = File.ReadAllBytes(path);
result.Content = new StreamContent(excelData);

You can give a try with this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!