Download Excel File using AJAX in JavaScript

Hello Guys, In this blog post we are going to see how we can download an excel file using a javascript function.

I have added a HTML button on the page, When we click on HTML button, the javaScript function is called and the file name is passed as parameter to the javascript function. 

We will use XMLHttpRequest object to get the file data in binary format.

The onload event handler of the XMLHttpRequest object will convert the received Byte Array (Binary Data) into BLOB (Binary Large Object) object and the file is downloaded in the browser.

Create an empty .NET web application and add HTML page provide a name to the HTML file and add a sample excel file to the root of the application.

Below is the complete HTML code.


<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title></title>

</head>

<body>

    <input type="button" value="Download Excel File" onclick="DownloadFile('SampleExcel.xlsx');" />

    <script type="text/javascript">

        function DownloadFile(fileName) {

            //Set the file URL.

            var urlPath =fileName;

            //Create XMLHTTP Request.

            var request = new XMLHttpRequest();

            request.open("GET", urlPath, true);

            request.responseType = "blob";

            request.onload = function () {

                //Convert the Byte Data to BLOB object.

                var blob = new Blob([request.response],

{ type: "application/octetstream" });

                //Check the type of the browser and download the File.

                var isIE = false || !!document.documentMode;

                if (isIE) {

                    window.navigator.msSaveBlob(blob, fileName);

                }

else

{

                    var url = window.URL || window.webkitURL;

                    link = url.createObjectURL(blob);

                    var a = document.createElement("a");

                    a.setAttribute("download", fileName);

                    a.setAttribute("href", link);

                    document.body.appendChild(a);

                    a.click();

                    document.body.removeChild(a);

                }

            };

            request.send();

        };

    </script>

</body>

</html>



Comments

Popular posts from this blog

How to Capture Image using web camera in Asp.net and C#.NET / VB.NET

How to Install GIT ?