c# - 如何从 ASP.NET Core Web API web-app 返回 Excel 文件?

标签 c# http asp.net-web-api asp.net-core asp.net-core-1.0

在类似的问题中,使用此代码可以下载 PDF:

I'm testing with local files (.xlsx, .pdf, .zip) inside the Controller folder.

Similar Question Here

[HttpGet("downloadPDF")]
public FileResult TestDownloadPCF()
{
   HttpContext.Response.ContentType = "application/pdf";
   FileContentResult result = new FileContentResult
   (System.IO.File.ReadAllBytes("Controllers/test.pdf"), "application/pdf")
    {
      FileDownloadName = "test.pdf"
    };
   return result;
}

This works great!

但是当另一个文件?例如 Excel 文件 (.xlsx) 或 ZIP 文件 (.zip) 时,测试无法正常进行。

代码:

[HttpGet("downloadOtherFile")]
public FileResult TestDownloadOtherFile()
{
  HttpContext.Response.ContentType = 
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("Controllers/test.xlsx"), 
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  {
    FileDownloadName = "otherfile"
   };
  return result;
}

结果: enter image description here

我还使用以下 Content-Type 进行了测试:

  • “应用程序/vnd.ms-excel”
  • “应用程序/vnd.ms-excel.12”

得到相同的结果。

返回任何文件类型的正确方法是什么?

感谢您的回答

最佳答案

我的(工作)解决方案:

  • 我有一个使用 EPPlus.Core 动态创建 XLSX 文件的类。
    • 这将返回生成文件路径的 FileInfo

这是我的 Controller 中的内容:

[HttpGet("test")]
public async Task<FileResult> Get()
{
    var contentRootPath = _hostingEnvironment.ContentRootPath;

    // "items" is a List<T> of DataObjects
    var items = await _mediator.Send(new GetExcelRequest());

    var fileInfo = new ExcelFileCreator(contentRootPath).Execute(items);
    var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);

    const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Response.ContentType = contentType;
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    var fileContentResult = new FileContentResult(bytes, contentType)
    {
        FileDownloadName = fileInfo.Name
    };

    return fileContentResult;
}

这是我在 Angular2 中的内容:

downloadFile() {
    debugger;
    var headers = new Headers();
    headers.append('responseType', 'arraybuffer');

    let url = new URL('api/excelFile/test', environment.apiUrl);

    return this.http
        .get(url.href, {
            withCredentials: true,
            responseType: ResponseContentType.ArrayBuffer
        })
        .subscribe((response) => {
            let file = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            let fileName = response.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1];
            saveAs(file, fileName);
        },
        err => this.errorHandler.onError(err)
        );
}

关于c# - 如何从 ASP.NET Core Web API web-app 返回 Excel 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877195/

相关文章:

c# - 如何在属性参数中进行方法引用

c# - 更改在运行时添加的控件的属性

c# - 为什么我的帖子 JSON 对象没有被序列化?

c# - 更新到 Sharpdx 2.6.2 后无法编译 hlsl 着色器

为索引 0 插入优化的 C# 集合?

http - 如何将传入的 cookie 获取到 Mule HTTP 端点

c - 如何在C中逐行读取HTTP文件

apache - 将 URL 重定向到新地址但保留原始地址

java - NetworkSecurityConfig : No Network Security Config specified, 使用平台默认错误响应代码:400

c#-4.0 - 抱歉,这是另一个 : Found shared references to a collection