Export HTML Table to Word Document (doc) file using AngularJS in ASP.Net

Last Reply 7 days ago By dharmendr

Posted 8 days ago

How to export HTML table binded from database to Word file using angularjs in ASP.Net

Posted 7 days 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

<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, $window) {
        $http.post("Default.aspx/BindEmployees", { headers: { 'Content-Type': 'application/json'} })
        .then(function (response) {
            $scope.Employees = eval(response.data.d);
        });

        $scope.Export = function () {
            var html = angular.element(document.querySelector('#tblCustomer'))[0].innerHTML;
            var header = "<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
                        "xmlns:w='urn:schemas-microsoft-com:office:word' " +
                        "xmlns='http://www.w3.org/TR/REC-html40'>" +
                        "<head><meta charset='utf-8'><title>Export Table to Word</title></head><body>";
            var footer = "</body></html>";
            var sourceHTML = header + "<table border='1' cellpadding='1' cellspacing='1'>" + html + "</table>" + footer;
            if (navigator.msSaveBlob) { // IE 10+ 
                navigator.msSaveBlob(new Blob([sourceHTML], { type: 'application/vnd.ms-word' }), "Employee.doc");
            } else {
                var source = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(sourceHTML);
                var fileDownload = document.createElement("a");
                document.body.appendChild(fileDownload);
                fileDownload.href = source;
                fileDownload.download = 'Employee.doc';
                fileDownload.click();
                document.body.removeChild(fileDownload);
            }
        }
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <table id="tblCustomer">
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>City</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="employee in Employees">
                <td>{{ employee.EmployeeId }}</td>
                <td>{{ employee.FirstName }}</td>
                <td>{{ employee.LastName }}</td>
                <td>{{ employee.City }}</td>
                <td>{{ employee.Country }}</td>
            </tr>
        </tbody>
    </table>
    <br />
    <input type="button" value="Export" ng-click="Export()" />
</div>

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 BindEmployees()
{
    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
                    {
                        EmployeeId = sdr["EmployeeID"],
                        FirstName = sdr["FirstName"],
                        LastName = sdr["LastName"],
                        City = sdr["City"],
                        Country = sdr["Country"]
                    });
                }
            }
            conn.Close();
        }
        return (new JavaScriptSerializer().Serialize(employees));
    }
}

VB.Net

<WebMethod()> _
Public Shared Function BindEmployees() 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 {
                    .EmployeeId = sdr("EmployeeID"),
                    .FirstName = sdr("FirstName"),
                    .LastName = 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