Articles in this section
Category / Section

How to download an Excel file from Ajax call in ASP.NET Core?

4 mins read

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 documents from AJAX call in ASP.NET Core.

Steps to download an Excel file from Ajax call programmatically:

Step 1: Create a new ASP.NET Core web application project.

Create ASP.NET Core Web Application

Create ASP.NET Core Web Application

Step 2: Complete the ASP.NET Core Web Application – CreateXlsIOSample dialog:

  • Select Web Application (Model-View-Controller).
  • Click OK.

New ASP.NET Core Web Application dialog

New ASP.NET Core Web Application dialog

Step 3: Install the Syncfusion.XlsIO.Net.Core NuGet package as reference to your .NET Standard applications from NuGet.org.

Install NuGet package to the project

Install NuGet package to the project

Step 4: A default controller with name HomeController.cs gets added on creation of ASP.NET Core web application 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 and AJAX call, in the Index.cshtml as shown below.

CSHTML

@{
    ViewBag.Title = "Excel";
}
 
<h2>Click the button to download an Excel document from AJAX call</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") = "Excel"
End Code
 
<h2>Click the button to download an Excel document from AJAX call</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 8: Declare the variables _fileName and _filePath along with _hostingEnvironment and define them in the constructor of HomeController.

C#

private readonly IHostingEnvironment _hostingEnvironment;
private string _fileName;
private string _filePath; 
 
public HomeController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
    _fileName = "AjaxCall.xlsx";
    _filePath = string.Format("{0}/{1}", _hostingEnvironment.WebRootPath, _fileName);
}

 

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()
{
    //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;
        using (FileStream fileStream = new FileStream(_filePath, FileMode.Create, FileAccess.ReadWrite))
        {
            workbook.SaveAs(fileStream);
        }
    }
    var errorMessage = "you can return the errors here!";
    //Return the Excel file name
    return Json(new { _fileName, errorMessage });
}
 
[HttpGet]
public ActionResult Download(string fileName)
{
    byte[] fileByteArray = System.IO.File.ReadAllBytes(_filePath);
    System.IO.File.Delete(_filePath);
    return File(fileByteArray, "application/vnd.ms-excel", _fileName);
}

 

VB.NET

<HttpPost()>
Public Function ExportExcel() As ActionResult
    'Create an instance of ExcelEngine
    Dim 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
 
    Dim fileStream As FileStream = New FileStream(_filePath, FileMode.Create, FileAccess.ReadWrite)
    workbook.SaveAs(fileStream)
    Dim errorMessage = "you can return the errors here!"
 
    'Return the Excel file name
    Return Json(New Object() {_fileName, errorMessage})
End Function
 
<HttpGet()>
Public Function Download(ByVal fileName As String) As ActionResult
    Dim fileByteArray() As Byte = System.IO.File.ReadAllBytes(_filePath)
    System.IO.File.Delete(_filePath)
    Return File(fileByteArray, "application/vnd.ms-excel", _fileName)
End Function

 

A complete working example of how to create an Excel document from AJAX call in ASP.NET Core can be downloaded from Download Excel from AJAX call.zip.

By executing the program, you will get the output Excel file as shown below.

Excel file downloaded from AJAX call

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 download Excel from Ajax call in ASP.NET MVC?

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 C# example downloads Excel from Ajax call in ASP.NET Core.

You can refer to our XIsIO feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation 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 forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied