如果想知道 AngularJs 通过WebAPI 下载Excel。请看下文,这里仅提供了一种方案。
服务器端代码如下:
protected HttpResponseMessage GenereateExcelMessage(HttpRequestMessage Request, string fileName, string generatedFile)
{
if (System.IO.File.Exists(generatedFile))
{
var response = Request.CreateResponse(HttpStatusCode.OK);
System.IO.FileStream fileStream = new System.IO.FileStream(generatedFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
fileStream.CopyTo(ms);
response.Content = new ByteArrayContent(ms.ToArray());
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
客户端,可将以下代码放在Service里或者修改后放在Controller里
this.exportExcel = function (SearchOption) {
return $http.post('/api/XXXl', { paramenters: XX }, { responseType: "arraybuffer" }).then(function (response) {
var data = new Blob([response.data], { type: response.headers('Content-Type') });
var filename = response.headers('Content-Disposition').split(';')[1].trim().substr('filename='.length);
FileSaver.saveAs(data, filename);
});
};