0

I have created an excel file using NPOI and would like to send this through an API to make it downloadable from that webpage.

My question is that how do I in a good way send this excel file through my API? 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)

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

This is what I am using now to save the file.

Andrew Skirrow
  • 3,402
  • 18
  • 41
Yooric
  • 87
  • 8
  • 1
    It's not that clear exactly what you are asking. Are you creating a XLS file from a HTTP Controller or aspx page? Do you want it to be treated as a file download in the users browser -- or are you looking for something else? – Andrew Skirrow Nov 11 '20 at 11:40
  • Oh, sorry. I'll try to make it clearer. I am creating an xls file in c# in response to a api request from my website. As a response I would like to send back the excel. I don't know what to send it as and how to convert it. Yes, on the website I would like to be able to download it as an excel file =) – Yooric Nov 11 '20 at 11:47

1 Answers1

0

In general you can usually get a instance of class Stream that represents the client response and write to that instead of the file. You'd also want to set the correct Content-Type header.

For example in ASP.NET Core you could create you're own IActionResult implementation.

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. xls files are deprecated and can cause a number of issues.

Andrew Skirrow
  • 3,402
  • 18
  • 41
  • Thanks alot! I am trying this out =) – Yooric Nov 11 '20 at 12:36
  • await Workbook.WriteAsync(response.Body); Getting the error that my HSSFWorkbook doesn't have WriteAsync how would I use sync write as mentioned in the comment. – Yooric Nov 13 '20 at 13:38