[英]Webapi export to excel corrupted file downloaded
我使用 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;
客户端(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;
});
当我打开 Excel 时,我收到错误消息“Excel 在 Products.xlsx 中发现无法读取的内容,您是否要恢复此工作簿的内容......”。
我检查了 API 响应,发现 WebApi 以 OfficeOpenML 格式返回了一些数据,不确定这是否是问题所在
请帮我解决这个问题。 发现了一个类似的问题,没有得到解答。
我认为问题在于您将文件保存到流的方式,ExcelPackage 对象有自己的方法将其保存到内存流,我会像这样修复它:
使用 using 块
using (ExcelPackage xls = new ExcelPackage())
然后将其写入 MemoryStream
MemoryStream ms = new System.IO.MemoryStream();
xls.SaveAs(ms);
在关闭流之前将其写入您的响应
response.BinaryWrite(ms.ToArray());
ms.close(); //close the MemoryStream
那应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.