使用 EPPlus 返回 Task<IHttpActionResult> 中的 xlsx 数据

Jef*_*Fol 5 api excel xlsx epplus postman

我有一个基本的 web api,它试图返回一个作为下载操作而不是数据流触发的 excel 文档。关于创建流和设置附件属性,我已经在网上遵循了许多示例,但我的 Postman 请求始终显示为已编码。下面是API方法。

[Route("getexcel")]
[HttpPost]
public async Task<IHttpActionResult> GetExcel()
{
   IHttpActionResult result = null;
   FileInfo newFile = new FileInfo(@"C:\Test.xlsx");
   ExcelPackage pck = new ExcelPackage(newFile);

   HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
   response.Content = new ByteArrayContent(pck.GetAsByteArray());
   response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
   response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
   response.Content.Headers.ContentDisposition.FileName = "Test.xlsx";

   result = ResponseMessage(response);
   return result;
}
Run Code Online (Sandbox Code Playgroud)

从上面的代码中,如果我使用 MediaTypeHeaderValue("application/pdf") 然后邮递员请求显示下载请求,但对于 xlsx 格式或 application/octet-stream 它没有。相反,它显示了一个数据流。Content-Type 是 application/json,因为 api 的最终版本将在主体中获取 json 数据。

邮递员请求

Mik*_*nik 3

我可能会迟到,但是...“发送”按钮的下拉菜单中有“发送和下载” 在此输入图像描述