Webapi导出到excel损坏的文件下载

Sha*_*shi 5 javascript c# asp.net-web-api angularjs

我使用OfficeOpenXml ExcelPackage从对象列表生成excel这成功下载文件,但是当我打开文件时,excel会抱怨说它已损坏并且没有以正确的文件格式保存.我也试过使用FIleSaver.js,但也没有运气.同样的错误.对于如何解决这个问题,有任何的建议吗?

服务器代码:

 ExcelPackage _excelPackage = new ExcelPackage();
 ExcelWorksheet _sheet = _excelPackage.Workbook.Worksheets.Add("New Sheet");
 int currentRow = 1;
            foreach (var prod in Products)
            {
                 _sheet.Cells[currentRow, 0].Value = prod.Id;
                 _sheet.Cells[currentRow, 0].Value = prod.Name;
                 _sheet.Cells[currentRow, 0].Value = prod.Price;
                 currentRow++;
             }


HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);    
byte[] stream = _excelPackage.GetAsByteArray()
response.Content = new ByteArrayContent(stream);

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "Products.xlsx"
};
return response;
Run Code Online (Sandbox Code Playgroud)

客户端(AngularJS服务代码):

var req = {
    url: fpReportsWebAPIURL + 'api/Export/DownloadFile',
    method: 'POST',
    responseType: 'arraybuffer',
    //data: json, //this is your json data string
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
};

return $http(req).then(function (data) {
    var type = data.headers('Content-Type');
    var blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    saveAs(blob, 'Products' + '.xlsx');
    return true;
});
Run Code Online (Sandbox Code Playgroud)

当我打开Excel时,我收到错误,因为"Excel在Products.xlsx中找到了不可读的内容.你想要收回这个工作簿的内容.......".

我检查了API响应,发现WebApi以OfficeOpenML格式返回一些数据,不确定这是否是问题

请帮我解决这个问题.发现一个类似的问题没有答案.

the*_*nch 0

我认为问题在于将文件保存到流的方式,ExcelPackage 对象有它自己的方法将其保存到内存流,我会这样修复它:

使用 using 块

using (ExcelPackage xls = new ExcelPackage())
Run Code Online (Sandbox Code Playgroud)

然后将其写入MemoryStream

MemoryStream ms = new System.IO.MemoryStream();
xls.SaveAs(ms);
Run Code Online (Sandbox Code Playgroud)

在关闭流之前将其写入您的响应中

response.BinaryWrite(ms.ToArray());
ms.close(); //close the MemoryStream 
Run Code Online (Sandbox Code Playgroud)

那应该有效