ASP.NET Core直接在一个调用服务器(即时)中返回excel文件(xlsx)?

我已经find了在服务器上生成excel文件(xlsx)的解决scheme。首先调用它删除文件demo.xlsx,如果它存在并生成新的demo.xlsx。

首先调用http:// localhost:8000 / api / importexport / export

它生成excel文件(xlsx)并发送url进行下载

第二次调用http:// localhost:8000 / demo.xlsx

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

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

这个解决scheme的问题是我有两个调用服务器。 我想在一个叫http:// localhost:8000 / api / importexport / export的地方直接下载excel文件(xlsx)。 我听说可以在一个调用中下载excel文件(xlsx),而无需在服务器上创build文件(即时)。 我很高兴看到更好的解决scheme在一个电话到服务器。

这很容易,只需返回File (如ViewRedirect ,但File ):

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

这个方法是ControllerBase一部分,有几个签名,select最适合你的需求:

 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) 

这是我的解决scheme

  private readonly IHostingEnvironment _hostingEnvironment; public ImportExportController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } [HttpGet] [Route("Export")] public IActionResult Export() { string sWebRootFolder = _hostingEnvironment.WebRootPath; string sFileName = @"demo.xlsx"; string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName); FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); if (file.Exists) { file.Delete(); file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); } using (ExcelPackage package = new ExcelPackage(file)) { // add a new worksheet to the empty workbook ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee"); //First add the headers worksheet.Cells[1, 1].Value = "ID"; worksheet.Cells[1, 2].Value = "Name"; worksheet.Cells[1, 3].Value = "Gender"; worksheet.Cells[1, 4].Value = "Salary (in $)"; //Add values worksheet.Cells["A2"].Value = 1000; worksheet.Cells["B2"].Value = "Jon"; worksheet.Cells["C2"].Value = "M"; worksheet.Cells["D2"].Value = 5000; worksheet.Cells["A3"].Value = 1001; worksheet.Cells["B3"].Value = "Graham"; worksheet.Cells["C3"].Value = "M"; worksheet.Cells["D3"].Value = 10000; worksheet.Cells["A4"].Value = 1002; worksheet.Cells["B4"].Value = "Jenny"; worksheet.Cells["C4"].Value = "F"; worksheet.Cells["D4"].Value = 5000; package.Save(); //Save the workbook. } var result = PhysicalFile(Path.Combine(sWebRootFolder, sFileName), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment") { FileName = file.Name }.ToString(); return result; } 

如果有人有更好的解决scheme,请发布。