简体   繁体   English

寻找一种在c#低谷API中传输新创建的excel的好方法

[英]Looking for a good way to transfer a newly created excel in c# trough API

I have created an excel file using NPOI and would like to send this through an API to make it downloadable from that webpage.我已经使用 NPOI 创建了一个 excel 文件,并希望通过 API 发送它以使其可从该网页下载。

My question is that how do I in a good way send this excel file through my API?我的问题是,我如何以一种好的方式通过我的 API 发送这个 excel 文件? Can I store this excel file as a Blob or binary instead without saving it as a file to make it more easy to send it?(Don't want to save a file every time I am exporting an excel document)我可以将此 excel 文件存储为 Blob 或二进制文件而不将其保存为文件以使其更容易发送吗?(不想每次导出 excel 文档时都保存文件)

using (var fileData = new FileStream("ReportName.xls", FileMode.Create))
{
    workbook.Write(fileData);
}

This is what I am using now to save the file.这就是我现在用来保存文件的方法。

In general you can usually get a instance of class Stream that represents the client response and write to that instead of the file.通常,您通常可以获得代表客户端响应的类Stream的实例并写入该实例而不是文件。 You'd also want to set the correct Content-Type header.您还需要设置正确的Content-Type标头。

For example in ASP.NET Core you could create you're own IActionResult implementation.例如,在 ASP.NET Core 中,您可以创建自己的IActionResult实现。

public class XlsDownloadResult : IActionResult
{
     private readonly Workbook _workbook;

     public XlsDowloadResult(Workbook workbook) 
     {
           _workbook = workbook;
     }

     public async Task ExecuteResultAsync(ActionContext context)
     {
          var response = context.HttpContext.Response;
          response.Headers.Add("Content-Type", "application/vnd.ms-excel");
           
          // Assuming the workbook object has WriteAsync -- otherwise use sync write
          // and return Task.CompletedTask
          await _workbook.WriteAsync(response.Body);
     }
}

And then you can use it like this然后你可以像这样使用它

[HttpGet]
public IActionResult Get()
{
    var workbook = CreateWorkbook();
    return new XlsDownloadResult(workbook);
}

Finally -- I'd recommend you make sure you're creating xlsx files not xls files.最后——我建议你确保你创建的是xlsx文件而不是xls文件。 xls files are deprecated and can cause a number of issues. xls文件已弃用,可能会导致许多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM