Link to home
Start Free TrialLog in
Avatar of Rajkumar Gs
Rajkumar GsFlag for India

asked on

Download SSRS report as Excel File (AngularJs, C#, MVC)

I am working on a MVC project with AngularJs  and trying to download SSRS report as an excel. Am new to AngularJs.
I have tried the following codes and output is download excel with binary code!

Please correct my code, so that will download excel in exact same format as in SSRS report.

report-list.ctrl.js
(function () {
    'use strict';
    var module = angular.module('app')

        //.directive('ngConfirmClick', [
        //    function () {
        //        return {
        //            link: function (scope, element, attr) {
        //                var msg = attr.ngConfirmClick || "Are you sure?";
        //                var clickAction = attr.confirmedClick;
        //                element.bind('click', function (event) {
        //                    if (window.confirm(msg)) {
        //                        scope.$eval(clickAction)
        //                    }
        //                });
        //            }
        //        };
        //    }])

        .controller('ReportListController', ['$scope', '$http', '$q', '$interval', '$location', '$window', '$modal', '$modalStack', 'toastr', 'dataService',
            function ($scope, $http, $q, $interval, $location, $window, $modal, $modalStack, toastr, dataService) {

                $scope.showreportlist = true;
                $scope.reports = [];
                $scope.clientsessionreportData = [];


                $scope.downloadReport = function (res) {

                    var file = new Blob([res],  {  type:  'application/excel'  });
                        var  fileName  =  'ClientSessionReport.xls';

                        if  ($window.navigator  &&  $window.navigator.msSaveOrOpenBlob)  {
                                $window.navigator.msSaveOrOpenBlob(file,  fileName);
                        }  else  {
                                var  a  =  document.createElement('a');
                                a.href  =  URL.createObjectURL(file);
                                a.target  =  '_blank';
                                a.download  =  fileName;
                                document.body.appendChild(a);
                                a.click();
                        }
                } 


                $scope.getClientSessionReport = function (entity) {
                    $http({
                        method: 'GET',
                        url: absolutePath + 'api/Report/GetClientSessionReport?reportId=67',
                        data: {  }
                    }).success(function (data, status, headers, config) {
                        if (data.Status == 'Custom Error') {
                            alert(data.Message);
                        }
                        else if (data.Status == 'Error') {
                            alert(data.Message);
                        }
                        else {
                            $scope.downloadReport(data.Data)
                        }
                    }.bind(this)).error(function (data, status, headers, config) {
                        if (data.Status == 'Custom Error') {
                            alert(data.Message);
                        }
                        else {
                            alert('Unexpected Error while saving data!!');
                        }
                    });

                };

                $scope.getReports = function () {
                    $http({
                        method: 'GET',
                        url: absolutePath + 'api/Report/GetReports',
                        data: {}

                    }).success(function (data, status, headers, config) {
                        if (data.Status == 'Custom Error') {
                            alert(data.Message);
                        }
                        else if (data.Status == 'Error') {
                            alert(data.Message);
                        }
                        else {
                            jQuery.each(data.Data, function (index, item) {
                                $scope.reports.push({ "Name": item.ReportName });
                            });
                        }
                    }.bind(this)).error(function (data, status, headers, config) {
                        if (data.Status == 'Custom Error') {
                            alert(data.Message);
                        }
                        else {
                            alert('Unexpected Error while saving data!!');
                        }
                    });

                };

                $scope.getReports();


                $scope.gridOpts = {
                    showFooter: true,
                    enableSorting: false,
                    multiSelect: false,
                    enableFiltering: false,
                    enableCellEdit: false,
                    enableRowSelection: false,
                    enableSelectAll: false,
                    enableRowHeaderSelection: false,
                    selectionRowHeaderWidth: 35,
                    noUnselect: true,
                    enableGridMenu: false,
                    paginationPageSizes: [5, 10, 15],
                    paginationPageSize: 9,
                    "enablePagination": true,
                    "enablePaginationControls": true,

                    appScopeProvider: $scope.myAppScopeProvider,

                    columnDefs: [
                        {
                            field: 'Name',
                            enableCellEdit: false,
                            displayName: 'Report Name'
                        },
                        {
                            name: 'actions',
                            enableSorting: false,
                            enableFiltering: false,
                            displayName: 'Actions',
                            width: '10%',
                            align: 'center',
                            cellTemplate: '<button id="downloadBtn" type="button" class="btn btn-small btn-primary" confirmed-click="grid.appScope.getClientSessionReport(row.entity)" ng-confirm-click="Are you sure to start download the selected report ?"  >Download</button>'
                        },
                    ]
                };

                $scope.gridOpts.data = $scope.reports;
            }]


        )
})();

Open in new window


ReportController.cs
[Route("api/Report/GetClientSessionReport")]
        public ReportDTO GetClientSessionReport(long reportId)
        {
            var result = new ReportDTO();
            //HttpResponseMessage response;
            try
            {
                result.Data = _reportService.GetClientSessionReport(reportId);
                result.Status = "Success";
            }
            catch (TIEOException ve)
            {
                result.Status = "Custom Error";
                result.Message = ve.Message;
            }
            catch (Exception ex)
            {
                result.Status = "Error";
                result.Message = ex.ToString();
            }
            return result;
        }

Open in new window


ReportService.cs
public byte[] GetClientSessionReport(long reportId)
        {
            var credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ReportUserName"], ConfigurationManager.AppSettings["ReportPassword"]);

            using (var handler = new HttpClientHandler { Credentials = credentials })
            {
                using (var client = new HttpClient(handler))
                {
                    string url = HttpUtility.HtmlDecode(ConfigurationManager.AppSettings["ReportUrl"]);
                    url = url.Replace("{sesionId}", reportId.ToString());

                    string dbName = HttpUtility.HtmlDecode(ConfigurationManager.AppSettings["SessionDatabaseInstanceName"]);
                    url = url.Replace("{DBName}", dbName.ToString());

                    var response = client.GetStreamAsync(url);
                    response.Wait();
                    using (MemoryStream ms = new MemoryStream())
                    {
                        response.Result.CopyTo(ms);
                        return ms.ToArray();
                    }
                }
            }
        }

Open in new window


Downloaded excel contains the byte array data as it is. Not got converted to SSRS report's view
ASKER CERTIFIED SOLUTION
Avatar of Rajkumar Gs
Rajkumar Gs
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rajkumar Gs

ASKER

I got solution by assistance of one my colleague, which I am marking as the solution.

Excel download now correctly (Junk data can be ignore, it is as it is in database and expected)
 [embed=file 1348970]
Excel-Correct-Format.PNG