For modern .xlsx files, use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet . For older .xls files, use application/vnd.ms-excel .
To download an Excel file from a byte array in C# ASP.NET MVC, you primarily use the File method within a controller action to return a FileContentResult . This approach is efficient for files generated in memory using libraries like EPPlus or ClosedXML . Implementation Guide 1. Controller Action Setup
using (var package = new ExcelPackage()) { var sheet = package.Workbook.Worksheets.Add("MySheet"); sheet.Cells["A1"].Value = "Hello World"; // Convert the package to a byte array return package.GetAsByteArray(); } Use code with caution. download excel file from byte array c# mvc
using (var workbook = new XLWorkbook()) { var worksheet = workbook.Worksheets.Add("Sample Sheet"); worksheet.Cell("A1").Value = "Data Content"; using (var stream = new MemoryStream()) { workbook.SaveAs(stream); return stream.ToArray(); // Returns the byte array } } Use code with caution. Key Components for Success
The most direct way to trigger a download is by returning a File object that takes the byte array, the MIME type, and the desired file name. For modern
If you are creating the Excel file dynamically, you will typically use a MemoryStream to capture the workbook data and then convert it to an array.
Use a standard HTML link or a form submission. Note that AJAX requests do not naturally trigger browser "Save As" dialogs; for AJAX, you may need to create a Blob object in JavaScript to handle the download on the client side. Summary Table: Common Download Methods Requirement Method to Use Return Type From Byte Array File(byteArray, contentType, fileName) FileContentResult From Stream File(fileStream, contentType, fileName) FileStreamResult From Local Path File(filePath, contentType, fileName) FilePathResult Return Excel File from Controller in ASP.Net MVC This approach is efficient for files generated in
Your action method should ideally return FileResult or ActionResult to allow the MVC framework to handle the response headers correctly.