How to return an Excel file from ASP.NET Core Web API web-app?

后端 未结 4 1705
情话喂你
情话喂你 2020-12-31 09:47

In similar questions, with this code works to download a PDF:

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

4条回答
  •  旧时难觅i
    2020-12-31 10:37

    Following is an example of how you can download a file, you can model your scenario of downloading an Excel file after it:

    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");
    }
    

    If the file is in the wwwroot folder, you could do something like below instead:

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

提交回复
热议问题