如果想知道 AngularJs 通過WebAPI 下載Excel。請看下文,這裡僅提供了一種方案。 伺服器端代碼如下: protected HttpResponseMessage GenereateExcelMessage(HttpRequestMessage Request, string fil
如果想知道 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); }); };