简体   繁体   中英

Download data as Excel file using web api and angular JS

I have a scenario to download file from the web app that uses a) Angular JS as front end b) Web api as server and the browser is IE9.

I have tried lot of plugins for converting HTML table to excel,csv but none of them worked for IE9.So i have decided generate the file in web api and download in the client.But that too does not work. Can any one share an working example for this scenario ? Angular JS Code:

var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope, exportToExcelService) {
        $scope.export = function () {
            exportToExcelService.download().success(
                function (response) {

                })
                 .error(function (response, status) {

                 });
        }
    }).

factory('exportToExcelService', function ($http) {
    var sampleAPI = {};
    sampleAPI.download = function () {
        return $http({
            method: 'POST',
            url: 'api/Sample/download'          
        });
    }
    return sampleAPI;
});

Web APi Controller code:

[HttpPost]
        public HttpResponseMessage download()
        {
            List<Record> obj = new List<Record>();
            obj = RecordInfo();
            StringBuilder str = new StringBuilder();
            str.Append("<table border=`" + "1px" + "`b>");
            str.Append("<tr>");
            str.Append("<td><b><font face=Arial Narrow size=3>FName</font></b></td>");
            str.Append("<td><b><font face=Arial Narrow size=3>LName</font></b></td>");
            str.Append("<td><b><font face=Arial Narrow size=3>Address</font></b></td>");
            str.Append("</tr>");
            foreach (Record val in obj)
            {
                str.Append("<tr>");
                str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.FName.ToString() + "</font></td>");
                str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.LName.ToString() + "</font></td>");
                str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Address.ToString() + "</font></td>");
                str.Append("</tr>");
            }
            str.Append("</table>");
            HttpResponseMessage result = null;
            // serve the file to the client      
            result = Request.CreateResponse(HttpStatusCode.OK);
            byte[] array = Encoding.ASCII.GetBytes(str.ToString());
            MemoryStream mem = new MemoryStream(array);
            result.Content = new StreamContent(mem);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Data.xls"
            };
            return result;
        }

        public List<Record> RecordInfo()
        {

            List<Record> recordobj = new List<Record>();
            recordobj.Add(new Record { FName = "Smith", LName = "Singh", Address = "Knpur" });
            recordobj.Add(new Record { FName = "John", LName = "Kumar", Address = "Lucknow" });
            recordobj.Add(new Record { FName = "Vikram", LName = "Kapoor", Address = "Delhi" });
            recordobj.Add(new Record { FName = "Tanya", LName = "Shrma", Address = "Banaras" });
            recordobj.Add(new Record { FName = "Malini", LName = "Ahuja", Address = "Gujrat" });
            recordobj.Add(new Record { FName = "Varun", LName = "Katiyar", Address = "Rajasthan" });
            recordobj.Add(new Record { FName = "Arun  ", LName = "Singh", Address = "Jaipur" });
            recordobj.Add(new Record { FName = "Ram", LName = "Kapoor", Address = "Panjab" });
            return recordobj;
        }

I found the solution by using the following code and it works like a charm.We just need to add window.location.href.

app.controller('myCtrl', function ($scope, exportToExcelService,$location) {
    $scope.export = function () {
        exportToExcelService.download().success(
            function (response) {                
               window.location.href = 'api/sample/download'
            })
             .error(function (response, status) {
                 var str = 'Hello'
             });
    }
}).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM