WebApi使用EF EPPlus返回乱码乱码

时间:2016-10-07 14:03:49

标签: asp.net-web-api epplus

我试图在我的EF WebApi中使用EPPlus来返回excel工作簿中的数据。 对Web服务器的调用成功完成,但是当我的浏览器打开excel文档时...所有内容都是乱码。

这是我的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;
        }
    }

这是截图 enter image description here

新的错误消息

<?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 个答案:

答案 0 :(得分:3)

EPPlus创建.xlsx文件 - 将文件扩展名从.xls更改为.xlsx