How to Export an Excel File using C#

Helo, i already search on Google and here (StackOverflow) but no any solution i complete.

I Have a Excel file in my folder and i need to create a method on my controller to download this file.

And in my React Web Site i need to get this file to user computer.

I try to use ActionResult, FileStreamResult, HttpResponseMessage and other, read file from folder with File.ReadAllbytes, put the Header on response.

On the final i get this.

{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}

And using this JavaScript do download:

var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
                var blob = new Blob([bytes], {
                    type: responseDownloadFile.data.ContentType
                });

                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = responseDownloadFile.data.FileDownloadName;
                document.body.appendChild(link);
                link.click();

But the file when download is corrupted.

Any on can help me?

1 answer

  • answered 2020-10-30 05:34 eldu_gate

    Try to return HttpResponseMessage type on your API

                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent([file bytes]);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "filename.xlsx"
                };
    
                return result;
    

    And on your Front end execute code:

    window.location.href = "link to your api endpoint to download excel";