How to download excel from Ajax call in ASP.NET MVC?
Syncfusion Excel (XlsIO) library is a .NET Excel library used to create, read, and edit Excel documents. Using this library, you can create and download Excel document from AJAX call in ASP.NET MVC.
Steps to download an Excel file from Ajax call programmatically:
Step 1: Create a new ASP.NET web application project.
Create a new ASP.NET web application
Step 2: Complete the New ASP.NET Web Application – CreateXlsIOSample dialog:
- Select MVC.
- Click OK.
New ASP.NET Web Application dialog
Step 3: Install the Syncfusion.XlsIO.AspNet.Mvc5 NuGet package as reference to your .NET Framework application from NuGet.org.
Install NuGet package
Step 4: A default controller with name HomeController.cs gets added on creation of ASP.NET MVC project. Include the following namespace in that HomeController.cs file.
C#
using Syncfusion.XlsIO;
VB.NET
Imports Syncfusion.XlsIO
Step 5: A default action method named Index will be present in HomeController.cs. Right click on this action method and select Go To View where you will be directed to its associated view page Index.cshtml.
Step 6: Add a new button in the Index.cshtml and add AJAX call as shown below.
CSHTML
@{ ViewBag.Title = "View"; } <h2>View</h2> <input type="button" onclick="exported()" value="Export" /> <script> function exported(e) { $.ajax({ type: "POST", url: '@Url.Action("ExportExcel", "Home")', //call your controller and action contentType: "application/json; charset=utf-8", dataType: "json", }).done(function (data) { //get the file name for download if (data.fileName != "") { //use window.location.href for redirect to download action for download the file window.location.href = "@Url.RouteUrl(new { Controller = "Home", Action = "Download" })/?fileName=" + data.fileName; } }); } </script>
VBHTML
@Code ViewData("Title") = "View" End Code <h2>View</h2> <input type="button" onclick="exported()" value="Export" /> <script> function exported(e) { $.ajax({ type: "POST", url: '@Url.Action("ExportExcel", "Home")', //call your controller and action contentType: "application/json; charset=utf-8", dataType: "json", }).done(function (data) { //get the file name for download if (data.fileName != "") { //use window.location.href for redirect to download action for download the file window.location.href = "@Url.RouteUrl(New With {.Controller = "Home", .Action = "Download"})/?fileName=" + data.fileName; } }); } </script>
Step 7: Include the below methods ExportExcel and Download in HomeController.cs to create an Excel file and download it through AJAX call.
C#
[HttpPost] public ActionResult ExportExcel() { var fileName = "AjaxCall" + ".xlsx"; //Save the file to server temp folder string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName); //Create an instance of ExcelEngine using (ExcelEngine excelEngine = new ExcelEngine()) { //Set the default application version as Excel 2016 excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2016; //Create a workbook with a worksheet IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1); //Access first worksheet from the workbook instance IWorksheet worksheet = workbook.Worksheets[0]; //Insert sample text into cell “A1” worksheet.Range["A1"].Text = "Hello World!"; //Save the workbook to disk in xlsx format workbook.Version = ExcelVersion.Excel2016; workbook.SaveAs(fullPath); } var errorMessage = "you can return the errors here!"; //Return the Excel file name return Json(new { fileName = fileName, errorMessage }); } [HttpGet] public ActionResult Download(string fileName) { //Get the temp folder and file path in server string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName); byte[] fileByteArray = System.IO.File.ReadAllBytes(fullPath); System.IO.File.Delete(fullPath); return File(fileByteArray, "application/vnd.ms-excel", fileName); }
VB.NET
Function ExportExcel() As ActionResult Dim fileName = "AjaxCall" & ".xlsx" 'Save the file to server temp folder Dim fullPath As String = Path.Combine(Server.MapPath("~/temp"), fileName) 'Create an instance of ExcelEngine Using excelEngine As ExcelEngine = New ExcelEngine 'Set the default application version as Excel 2016 excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2016 'Create a workbook with a worksheet Dim workbook As IWorkbook = excelEngine.Excel.Workbooks.Create(1) 'Access first worksheet from the workbook instance Dim worksheet As IWorksheet = workbook.Worksheets(0) 'Insert sample text into cell “A1” worksheet.Range("A1").Text = "Hello World!" 'Save the workbook to disk in xlsx format workbook.Version = ExcelVersion.Excel2016 workbook.SaveAs(fullPath) End Using Dim errorMessage = "you can return the errors here!" 'Return the Excel file name Return Json(New With {Key .fileName = fileName, errorMessage}) End Function Function Download(ByVal fileName As String) As ActionResult 'Get the temp folder and file path in server Dim fullPath As String = Path.Combine(Server.MapPath("~/temp"), fileName) Dim fileByteArray As Byte() = System.IO.File.ReadAllBytes(fullPath) System.IO.File.Delete(fullPath) Return File(fileByteArray, "application/vnd.ms-excel", fileName) End Function
A complete working example of how to create an Excel file from AJAX call in ASP.NET MVC can be downloaded from Download Excel from AJAX call.zip.
By executing the program, you will get the output Excel file as shown below.
Output Excel document
Refer here to explore the rich set of Syncfusion Excel (XlsIO) library features.
An online sample link to generate` Excel file.
See Also:
How to download Excel from Ajax call in ASP.NET?
How to create an Excel file in ASP.NET MVC?
How to create an Excel file in ASP.NET Core?
How to create an Excel file in ASP.NET Web Forms?
How to download the uploaded file in browser?
How to generate and display Excel files in thumbnail view?
Note:
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer the link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.
Conclusion
I hope you enjoyed learning about how to download excel from Ajax call in ASP.NET MVC.
You can refer to our ASP.NET MVC Menu feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Menu example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!