使用web api和angular JS将数据下载为Excel文件

时间:2015-10-28 09:59:32

标签: javascript angularjs excel asp.net-web-api

我有一个从Web应用程序下载文件的方案,该应用程序使用a)Angular JS作为前端b)Web api作为服务器,浏览器是IE9。

我已经尝试了很多用于将HTML表格转换为excel,csv的插件,但它们都没有适用于IE9。所以我决定在web api中生成文件并在客户端下载。但是这也无法正常工作。 任何人都可以分享这个场景的工作示例吗? Angular JS代码:

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控制器代码:

[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;
        }

1 个答案:

答案 0 :(得分:1)

我通过使用以下代码找到了解决方案,它就像一个魅力。我们只需要添加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'
             });
    }
}).