WebApi using EF EPPlus returning gibberish in exce

2019-07-26 23:28发布

I am trying to use EPPlus in my EF WebApi to return data in a excel workbook. The call to webserver gets made successfully, but when my browser opens the excel doc... all the content is gibberish.

This is my webapi

        private xxxV003Context db = new xxxV003Context();

    [HttpGet]
    public HttpResponseMessage Get()
    {
        HttpResponseMessage response;
        response = Request.CreateResponse(HttpStatusCode.OK);
        MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/octet-stream");
        //MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.Content = new StreamContent(ExcelSheet());
        response.Content.Headers.ContentType = mediaType;
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = "Orders.xlsx";
        return response;
    }

    public List<Client> Orders()
    {
        List<Client> tList = new List<Client>();
        using (db)
        {
            tList.Add(new Client { ClientID = 50, ClientName = "testName1" });
            tList.Add(new Client { ClientID = 51, ClientName = "testName2" });
        }
        return tList;
    }

    public MemoryStream ExcelSheet()
    {
        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Orders");
            worksheet.Cells["A1"].LoadFromCollection(Orders(), false);
            package.Save();
            var stream = new MemoryStream(package.GetAsByteArray());
            return stream;
        }
    }

here is the screenshot enter image description here

NEW ERROR MESSAGE

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<recoveryLog     xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error125800_03.xml</logFileName>
<summary>Errors were detected in file 'C:\Users\xxx\Downloads\Orders   (2).xlsx'</summary>
-<additionalInfo>
<info>Excel completed file level validation and repair. Some parts of this    workbook may have been repaired or discarded.</info>
</additionalInfo>
</recoveryLog>

1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-26 23:43

EPPlus creates .xlsx files - Change the file extension from .xls to .xlsx

查看更多
登录 后发表回答