Excel等格式檔案從服務端呼叫匯出
阿新 • • 發佈:2020-08-26
服務端實現
/// <summary> /// Excel檔案 /// </summary> /// <param name="requestDto">請求引數</param> /// <returns></returns> [HttpPost("[action]")] public async Task<FileResult> XXXExcelStream([FromBody] XXXQueryRequestDto requestDto) { byte[] bytes = await new XXXService(this).GetXXXExcelInfo(requestDto); if (bytes == null) { return null; } return File(bytes, "application/octet-stream", $"XXX資料{System.DateTime.Now:yyyyMMddHHmmss}.xlsx"); } /// <summary> /// Excel陣列 /// </summary> /// <param name="requestDto">請求引數</param> /// <returns></returns> [HttpPost("[action]")] public async Task<ActionResult<byte[]>> XXXExcelInfo([FromBody] XXXQueryRequestDto requestDto) { byte[] bytes = await new XXXService(this).GetXXXExcelInfo(requestDto); return bytes; }
客戶端呼叫
private async Task BtnExportClickAsnc(XXXRequestDto dto, string fileName) { var response = XXXAPI.XXXExcelStreamWithHttpMessagesAsync(dto); Stream stream = await response.Response.Content.ReadAsStreamAsync(); if (stream != null) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { await stream.CopyToAsync(fs); fs.Flush(); } } } private async Task BtnExportClickAsnc(XXXRequestDto dto, string fileName) { var response = XXXAPI.XXXExcelInfoWithHttpMessagesAsync(dto); try { byte[] data = response.Body; File.WriteAllBytes(fileName, data); } catch (Exception ex) { } }