Export HTML Table to CSV file using AngularJS in ASP.Net

Last Reply 4 months ago By dharmendr

Posted 4 months ago

How to export HTML Table to CSV using angularjs in ASP.net

Posted 4 months ago

Hi rani,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', function ($scope, $http) {
            $http.post("Default.aspx/GetEmployees", { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                $scope.Employees = eval(response.data.d);
            }, function error(response) {
                alert(response.responseText);
            });

            $scope.Export = function () {
                var rows = document.getElementById("tblEmployees").rows;
                var data = "";
                for (var row = 0; row < rows.length; row++) {
                    for (var column = 0; column < rows[row].cells.length; column++) {
                        data += rows[row].cells[column].innerHTML.trim() + ",";
                    }
                    data += "\n";
                }
                if (navigator.msSaveBlob) {
                    navigator.msSaveBlob(new Blob([data], { type: 'text/csv;charset=utf-8;' }), "Employee.csv");
                } else {
                    var a = document.createElement("a");
                    a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(data);
                    a.target = '_blank';
                    a.download = 'sample.csv';
                    document.body.appendChild(a);
                    a.click();
                }
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-app="MyApp" ng-controller="MyController">
        <table id="tblEmployees">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in Employees">
                    <td>{{employee.Id}}</td>
                    <td>{{employee.Name}}</td>
                    <td>{{employee.City}}</td>
                    <td>{{employee.Country}}</td>
                </tr>
            </tbody>
        </table>
        <br />
        <input type="button" value="Export" ng-click="Export()" />
    </div>
    </form>
</body>
</html>

Namespaces

C#

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

VB.Net

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Services

Code

C#

[WebMethod]
public static string GetEmployees()
{
    List<object> employees = new List<object>();
    string sql = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees";
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand(sql))
        {
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(new
                    {
                        Id = sdr["EmployeeID"],
                        Name = sdr["FirstName"] + " " + sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

<WebMethod()>
Public Shared Function GetEmployees() As String
    Dim employees As List(Of Object) = New List(Of Object)()
    Dim sql As String = "SELECT EmployeeID,FirstName,LastName,City,Country FROM Employees"
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand(sql)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    employees.Add(New With { _
                    .Id = sdr("EmployeeID"),
                    .Name = sdr("FirstName") & " " & sdr("LastName"),
                    .City = sdr("City"),
                    .Country = sdr("Country")
                })
                End While
            End Using
            conn.Close()
        End Using

        Return (New JavaScriptSerializer().Serialize(employees))
    End Using
End Function

Screenshot