issue with returning HttpResponseMessage as excel file in WebAPI

后端 未结 2 809
孤街浪徒
孤街浪徒 2021-01-25 12:10

I have created WebAPI which returns an excel file using closedxml nuget. Basically it converts my DataTable to excel. I\'m referring couple of links below,

相关标签:
2条回答
  • 2021-01-25 12:49

    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.

    0 讨论(0)
  • 2021-01-25 13:02

    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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题