本文介绍了ASP.NET Core一次调用服务器(即时)直接返回excel文件(xlsx)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了在服务器上生成excel文件(xlsx)的解决方案.第一次调用时,它将删除文件demo.xlsx(如果存在)并生成新的demo.xlsx.

I have found solution for generating excel file (xlsx) on the server.On first call it deletes the file demo.xlsx if it exists and generates new demo.xlsx.

首次通话 http://localhost:8000/api/importexport/export

它会生成Excel文件(xlsx)并发送要下载的网址

it generates excel file (xlsx) and sends url for download

第二通电话 http://localhost:8000/demo.xlsx

下载文件.在Configure方法的Startup类中,您必须添加app.UseStaticFiles();

downloads the file.In Startup class in Configure method you must add app.UseStaticFiles();

这是解决方案的链接 http://www.talkingdotnet.com/import-export-xlsx- asp-net-core/

Here is the link for solutionhttp://www.talkingdotnet.com/import-export-xlsx-asp-net-core/

此解决方案的问题是我有两个服务器呼叫.我要一个电话 http://localhost:8000/api/importexport/export 直接下载excel文件(xlsx).我听说可以在一次调用中下载excel文件(xlsx),而无需在服务器上动态创建文件.我很高兴在一次致电服务器中看到更好的解决方案.

The problem with this solution is that I have two calls to server.I want in one callhttp://localhost:8000/api/importexport/export to directly download excel file (xlsx).I heard that its possible to download excel file (xlsx) in one call without creating file on the server(on the fly).I would be glad to see better solution in one call to the server.

推荐答案

很简单,只需返回File(类似于ViewRedirect,但File):

It's easy, just return File (like of View or Redirect, but File):

public async Task<ActionResult> Index()
{
    var fileMemoryStream = await GenerateReportAndWriteToMemoryStream(...);
    return File(
        fileMemoryStream, 
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
        "report.xlsx");
}

该方法是ControllerBase ,并且具有多个签名,请选择最符合您需求的签名:

This method is part of ControllerBase and has several signatures, choose best that fit your needs:

File(byte[] fileContents, string contentType)
File(Stream fileStream, string contentType)
File(string virtualPath, string contentType)
File(string virtualPath, string contentType, string fileDownloadName)
File(byte[] fileContents, string contentType, string fileDownloadName)
File(Stream fileStream, string contentType, string fileDownloadName)

这篇关于ASP.NET Core一次调用服务器(即时)直接返回excel文件(xlsx)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 06:11