在Angularjs和WebApi中下载Excel文件

时间:2015-08-20 22:40:40

标签: angularjs excel export-to-excel

这成功下载了文件,但是当我打开文件时,excel会抱怨说它已损坏并且没有以适当的文件格式保存。我也试过使用FIleSaver.js,但也没有运气。同样的错误。 有关如何解决此问题的任何建议吗?

服务器代码:

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);    
FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
response.Content = new ByteArrayContent(ms.ToArray());

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

response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = fileInfo.Name
};
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, 'helloAgain' + '.xlsx');
    return true;
});

0 个答案:

没有答案