【发布时间】:2016-01-19 13:23:17
【问题描述】:
我使用 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 格式的数据,不确定这是否是问题
请帮我解决这个问题。发现了一个类似的问题,没有答案。
【问题讨论】:
-
如果我能找到任何答案将在这里发布.. 仍在搜索
-
找到的解决方案请参考以下链接希望对其他人有所帮助stackoverflow.com/a/28148359/5475124
标签: javascript c# angularjs asp.net-web-api