Articles in this section
Category / Section

How to download ASP.NET Web Forms XlsIO from Ajax call?

5 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 an Excel file from an AJAX call in ASP.NET Web Forms.

Steps to create and download an Excel file from an AJAX call programmatically:

Step 1: Create a new ASP.NET Web application.

Create ASP.NET Web Forms application in Visual Studio

Create a new ASP.NET web application

Step 2: Install the Syncfusion.XlsIO.AspNet NuGet package as a reference to your .NET Framework application from NuGet.org.

Add XlsIO reference to the project

Install the NuGet package

Step 3: Add a new button in the Default.aspx file and add an AJAX call as shown below.

CSHTML

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
 
 <input type="button" onclick="exported()" value="Export"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script>
 
    function exported(e) {
        $.ajax({
            type: "POST",
            url: '/api/AjaxAPI/ExportExcel', //call your controller and action
            contentType: "application/json; charset=utf-8",
            dataType: "json",
        }).done(function () {
                //Use window.location.href for redirecting to the download action to download the file
                window.location.href = '/api/AjaxAPI/Download';
        });
    }
    </script>
 
</asp:Content>

 

Step 4: Include the following namespace in the newly added AjaxAPI.cs file.

C#

using Syncfusion.XlsIO;

 

VB.NET

Imports Syncfusion.XlsIO

 

Step 5: Include the below methods ExportExcel() and Download() in AjaxAPI.cs, to create an Excel file and download it through an AJAX call.

C#

[HttpPost]
// POST api/<controller>
public void ExportExcel()
{
   // Save the file to the server temp folder
   string fullPath = Path.Combine(HostingEnvironment.MapPath("~") + FileName);
            
   using (ExcelEngine excelEngine = new ExcelEngine())
   {
      IApplication application = excelEngine.Excel;
 
      // Create a workbook with a worksheet
      IWorkbook workbook = application.Workbooks.Create(1);
 
      // Insert sample text into cell “A1”
      workbook.Worksheets[0]["A1"].Text = "Hello World";
 
      workbook.Version = ExcelVersion.Excel2016;
 
      // Save the workbook 
      workbook.SaveAs(fullPath);
   }
}
[HttpGet]
public HttpResponseMessage Download()
{
   // Get the temp folder and file path on the server
   string fullPath = Path.Combine(HostingEnvironment.MapPath("~") + FileName);
   byte[] fileByteArray = System.IO.File.ReadAllBytes(fullPath);
   System.IO.File.Delete(fullPath);
   var stream = new MemoryStream(fileByteArray);
   var content = new HttpResponseMessage(HttpStatusCode.OK)
   {
      Content = new StreamContent(stream)
   };
   content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");            
   return content;
}

 

VB.NET

<HttpPost>
Public Sub ExportExcel()
'Save the file to the server temp folder
   Dim fullPath As String = Path.Combine(HostingEnvironment.MapPath("~") & fileName)
 
   Using excelEngine As ExcelEngine = New ExcelEngine()
      Dim application As IApplication = excelEngine.Excel
 
      'Create a workbook with a worksheet
      Dim workbook As IWorkbook = application.Workbooks.Create(1)
 
      'Insert sample text into cell “A1”
      workbook.Worksheets(0)("A1").Text = "Hello World"
      workbook.Version = ExcelVersion.Excel2016
 
      'Save the workbook
      workbook.SaveAs(fullPath)
   End Using 
End Sub
<HttpGet>
Public Function Download() As HttpResponseMessage
   Dim fullPath As String = Path.Combine(HostingEnvironment.MapPath("~") & FileName)
   Dim fileByteArray As Byte() = System.IO.File.ReadAllBytes(fullPath)
        System.IO.File.Delete(fullPath)
   Dim stream = New MemoryStream(fileByteArray)
   Dim content = New HttpResponseMessage(HttpStatusCode.OK) With {
            .Content = New StreamContent(stream)
   }
   content.Content.Headers.ContentType = New MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
   Return content
End Function

 

A complete working example of how to create and download an Excel file from an AJAX call in ASP.NET can be downloaded from Create Excel file.zip.

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

Create Excel File

Output Excel document

Take a moment to peruse the documentation, where you can find basic worksheet data manipulation options along with features like Conditional Formatting, worksheet calculations through Formulas, adding Charts in worksheets or workbooks, organizing and analyzing data through Tables and Pivot Tables, appending multiple records to worksheet using Template Markers, and most importantly PDF and Image conversions with code examples.

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 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&reg; 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&reg; license key in your application to use the components without a trial message.

 


Note:

A new version of Essential Studio for ASP.NET is available. Versions prior to the release of Essential Studio 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio for ASP.NET. Although Syncfusion will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

Conclusion

I hope you enjoyed learning about download ASP.NET Web Forms XlsIO from Ajax call

You can refer to our XIsIO’s feature tour page to learn about its other groundbreaking features. Explore our UG documentation and online demos to understand how to manipulate data in Excel documents.

If you are an existing user, you can access our latest components from the License and Downloads page. For new users, you can try our 30-day free trial to check out XlsIO and other Syncfusion&reg; components.

If you have any queries or require clarification, please let us know in the comments below or contact us through our support forumsSupport Tickets, 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