我在Angular JS中创建了一个应用程序,用于通过$ http帖子下载Excel工作簿.
在下面的代码中,我以JSON的形式传递信息,并通过角度$ http帖子将其发送到服务器REST Web服务(java).Web服务使用JSON中的信息并生成Excel工作簿.在$ http post的成功主体内的响应中,我在该数据变量中获取二进制数据,但不知道如何转换它并下载为Excel文件.
谁能告诉我一些解决方案,将二进制文件转换为Excel文件并下载?
我的代码如下:
$http({
url: 'myweb.com/myrestService',
method: "POST",
data: json, //this is your json data string
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
// Here i'm getting excel sheet binary datas in 'data'
}).error(function (data, status, headers, config) {
});
Run Code Online (Sandbox Code Playgroud) 我使用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, …Run Code Online (Sandbox Code Playgroud)