如何从WebAPI ASP.NET Core返回Excel文件

Jos*_*res 12 c# http asp.net-web-api asp.net-core asp.net-core-1.0

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

我正在使用Controller文件夹中的本地文件(.xlsx,.pdf,.zip)进行测试.

类似的问题

[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;
}
Run Code Online (Sandbox Code Playgroud)

这很棒!

但是当另一个文件?,例如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;
}
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述

我还使用以下内容类型进行了测试:

  • "Application/vnd.ms-excel"
  • "Application/vnd.ms-excel.12"

获得相同的结果.

哪种方法可以返回任何文件类型?

谢谢你的回答

BCd*_*WEB 8

我的(有效的)解决方案:

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

这是我的控制器中的内容:

[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;
}
Run Code Online (Sandbox Code Playgroud)

这是我在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)
        );
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*lla 1

以下是如何下载文件的示例,您可以模仿下载 Excel 文件的场景:

public IActionResult Index([FromServices] IHostingEnvironment hostingEnvironment)
{
    var path = Path.Combine(hostingEnvironment.ContentRootPath, "Controllers", "TextFile.txt");
    return File(System.IO.File.OpenRead(path), contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}
Run Code Online (Sandbox Code Playgroud)

如果该文件位于该wwwroot文件夹中,您可以执行如下操作:

public IActionResult Index()
{
    return File(virtualPath: "~/TextFile.txt", contentType: "text/plain; charset=utf-8", fileDownloadName: "Readme.txt");
}
Run Code Online (Sandbox Code Playgroud)