Import Data From Excel To DB Using AngularJS And Web API 2

Introduction

In this article, we will explain how to import data from an Excel sheet to SQL Server database by using library named js-xlsx. In this demo, we are going to create a basic Application whose role is to show you the steps, which are used to achieve our goal. Prior to it, you need to have some basic knowledge on AngularJS, Web API2 and Entity Framework ORM. I hope, you will like my article.

In this article, we are going to

  • Create database.
  • Create Web API Application.
  • Configuring Entity Framework ORM.
  • Create controller.
  • AngularJS part.
  • Create HTML page.

Let’s start.

SQL database part

Here, you will find the scripts to create a database and table.

Create a database 

  1. USE [master]  
  2. GO  
  3.   
  4. /****** Object:  Database [DbEmployee]    Script Date: 3/25/2017 8:23:01 AM ******/  
  5. CREATE DATABASE [DbEmployee]  
  6.  CONTAINMENT = NONE  
  7.  ON  PRIMARY   
  8. NAME = N'DbEmployee', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  9.  LOG ON   
  10. NAME = N'DbEmployee_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  11. GO  
  12.   
  13. ALTER DATABASE [DbEmployee] SET COMPATIBILITY_LEVEL = 110  
  14. GO  
  15.   
  16. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  17. begin  
  18. EXEC [DbEmployee].[dbo].[sp_fulltext_database] @action = 'enable'  
  19. end  
  20. GO  
  21.   
  22. ALTER DATABASE [DbEmployee] SET ANSI_NULL_DEFAULT OFF   
  23. GO  
  24.   
  25. ALTER DATABASE [DbEmployee] SET ANSI_NULLS OFF   
  26. GO  
  27.   
  28. ALTER DATABASE [DbEmployee] SET ANSI_PADDING OFF   
  29. GO  
  30.   
  31. ALTER DATABASE [DbEmployee] SET ANSI_WARNINGS OFF   
  32. GO  
  33.   
  34. ALTER DATABASE [DbEmployee] SET ARITHABORT OFF   
  35. GO  
  36.   
  37. ALTER DATABASE [DbEmployee] SET AUTO_CLOSE OFF   
  38. GO  
  39.   
  40. ALTER DATABASE [DbEmployee] SET AUTO_CREATE_STATISTICS ON   
  41. GO  
  42.   
  43. ALTER DATABASE [DbEmployee] SET AUTO_SHRINK OFF   
  44. GO  
  45.   
  46. ALTER DATABASE [DbEmployee] SET AUTO_UPDATE_STATISTICS ON   
  47. GO  
  48.   
  49. ALTER DATABASE [DbEmployee] SET CURSOR_CLOSE_ON_COMMIT OFF   
  50. GO  
  51.   
  52. ALTER DATABASE [DbEmployee] SET CURSOR_DEFAULT  GLOBAL   
  53. GO  
  54.   
  55. ALTER DATABASE [DbEmployee] SET CONCAT_NULL_YIELDS_NULL OFF   
  56. GO  
  57.   
  58. ALTER DATABASE [DbEmployee] SET NUMERIC_ROUNDABORT OFF   
  59. GO  
  60.   
  61. ALTER DATABASE [DbEmployee] SET QUOTED_IDENTIFIER OFF   
  62. GO  
  63.   
  64. ALTER DATABASE [DbEmployee] SET RECURSIVE_TRIGGERS OFF   
  65. GO  
  66.   
  67. ALTER DATABASE [DbEmployee] SET  DISABLE_BROKER   
  68. GO  
  69.   
  70. ALTER DATABASE [DbEmployee] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  71. GO  
  72.   
  73. ALTER DATABASE [DbEmployee] SET DATE_CORRELATION_OPTIMIZATION OFF   
  74. GO  
  75.   
  76. ALTER DATABASE [DbEmployee] SET TRUSTWORTHY OFF   
  77. GO  
  78.   
  79. ALTER DATABASE [DbEmployee] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  80. GO  
  81.   
  82. ALTER DATABASE [DbEmployee] SET PARAMETERIZATION SIMPLE   
  83. GO  
  84.   
  85. ALTER DATABASE [DbEmployee] SET READ_COMMITTED_SNAPSHOT OFF   
  86. GO  
  87.   
  88. ALTER DATABASE [DbEmployee] SET HONOR_BROKER_PRIORITY OFF   
  89. GO  
  90.   
  91. ALTER DATABASE [DbEmployee] SET RECOVERY SIMPLE   
  92. GO  
  93.   
  94. ALTER DATABASE [DbEmployee] SET  MULTI_USER   
  95. GO  
  96.   
  97. ALTER DATABASE [DbEmployee] SET PAGE_VERIFY CHECKSUM    
  98. GO  
  99.   
  100. ALTER DATABASE [DbEmployee] SET DB_CHAINING OFF   
  101. GO  
  102.   
  103. ALTER DATABASE [DbEmployee] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  104. GO  
  105.   
  106. ALTER DATABASE [DbEmployee] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  107. GO  
  108.   
  109. ALTER DATABASE [DbEmployee] SET  READ_WRITE   
  110. GO   

Create a table 

  1. USE [DbEmployee]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[EmployeeTable]    Script Date: 3/25/2017 8:23:51 AM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[EmployeeTable](  
  15.     [EmployeeID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [FirstName] [varchar](50) NULL,  
  17.     [LastName] [varchar](50) NULL,  
  18.     [Gender] [varchar](50) NULL,  
  19.     [Designation] [nchar](10) NULL,  
  20.     [Salary] [intNULL,  
  21.     [City] [varchar](50) NULL,  
  22.     [Country] [varchar](50) NULL,  
  23.  CONSTRAINT [PK_EmployeeTable] PRIMARY KEY CLUSTERED   
  24. (  
  25.     [EmployeeID] ASC  
  26. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  27. ON [PRIMARY]  
  28.   
  29. GO  
  30.   
  31. SET ANSI_PADDING OFF  
  32. GO   

After creating the table, you can add some records. as shown below.

AngularJS

 Create your Web API Application

Open Visual Studio and select File >> New Project.

The "New Project" Window will pop up. Select ASP.NET Web Application (.NET Framework), name your project and click OK.

AngularJS

Now, new dialog will pop up to select the template. We are going to choose Web API template and click OK button.

AngularJS

After creating our project, we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

To add ADO.NET Entity Framework, right click on the project name, click Add > Add New Item. A dialog box will pop up. Inside Visual C#, select Data followed by ADO.NET Entity Data Model and enter the name for your Dbcontext model as DbEmployee. Finally click Add.

AngularJS

In this level, we are going to choose EF Designer from the database, as show below.

AngularJS

After clicking Next button, a dialog will pop up with the name connection properties. You need to enter your Server name and connect to a database panel, select database via dropdown List (DbEmployee). Now, click OK button.

AngularJS

Now, the dialog Entity Data Model Wizard will pop up for choosing an object, which we need to use. In our case, we are going to choose EmployeeTable and click Finish button. Finally we see that EDMX model generates EmployeeTable class.

AngularJS

Create a controller

Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> select Web API 2 Controller – Empty > click Add.

AngularJS

Enter Controller name (‘EmployeeController’).

AngularJS

EmployeeController.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Web.Http.Description;  
  8.   
  9. namespace ExcelToDB.Controllers  
  10. {  
  11.     [RoutePrefix("api/Employee")]  
  12.     public class EmployeeController : ApiController  
  13.     {  
  14.         //DbContext  
  15.         DbEmployeeEntities db = new DbEmployeeEntities();  
  16.   
  17.   
  18.         [Route("Save")]  
  19.         [HttpPost]  
  20.         [ResponseType(typeof(void))]  
  21.         public IHttpActionResult Save(List<EmployeeTable> employeeList)  
  22.         {  
  23.             if (!ModelState.IsValid)  
  24.             {  
  25.                 return BadRequest(ModelState);  
  26.             }  
  27.   
  28.             foreach(var data in employeeList)  
  29.             {  
  30.                 db.EmployeeTables.Add(data);  
  31.             }  
  32.             db.SaveChanges();  
  33.   
  34.             return StatusCode(HttpStatusCode.OK);  
  35.   
  36.         }  
  37.   
  38.     }  
  39. }   

As you can see, I am creating Save() action, which takes an employee list as a parameter. We will now save the data to an employee table.

AngularJS part

In order to create new js file, right click on Scripts folder > Add > JavaScript file.

AngularJS

ImportData.js 

  1. var app = angular.module('app', []);  
  2.   
  3. app.controller('Ctrl', ['$scope''$http'function ($scope, $http) {  
  4.   
  5.     $scope.selectedFile = null;  
  6.     $scope.msg = "";  
  7.   
  8.   
  9.     $scope.loadFile = function (files) {  
  10.   
  11.         $scope.$apply(function () {  
  12.   
  13.             $scope.selectedFile = files[0];  
  14.   
  15.         })  
  16.   
  17.     }  
  18.   
  19.         $scope.handleFile = function () {  
  20.   
  21.         var file = $scope.selectedFile;  
  22.   
  23.         if (file) {  
  24.   
  25.             var reader = new FileReader();  
  26.   
  27.             reader.onload = function (e) {  
  28.   
  29.                 var data = e.target.result;  
  30.   
  31.                 var workbook = XLSX.read(data, { type: 'binary' });  
  32.   
  33.                 var first_sheet_name = workbook.SheetNames[0];  
  34.   
  35.                 var dataObjects = XLSX.utils.sheet_to_json(workbook.Sheets[first_sheet_name]);  
  36.   
  37.                 //console.log(excelData);  
  38.   
  39.                 if (dataObjects.length > 0) {  
  40.   
  41.                       
  42.                     $scope.save(dataObjects);  
  43.   
  44.   
  45.                 } else {  
  46.                     $scope.msg = "Error : Something Wrong !";  
  47.                 }  
  48.   
  49.             }  
  50.   
  51.             reader.onerror = function (ex) {  
  52.   
  53.             }  
  54.   
  55.             reader.readAsBinaryString(file);  
  56.         }  
  57.     }  
  58.   
  59.       
  60.     $scope.save = function (data) {  
  61.   
  62.         $http({  
  63.             method: "POST",  
  64.             url: "api/Employee/Save",  
  65.             data: JSON.stringify(data),  
  66.             headers: {  
  67.                 'Content-Type''application/json'  
  68.             }  
  69.   
  70.         }).then(function (data) {  
  71.             if (data.status) {  
  72.                 $scope.msg = "Data has been inserted ! ";  
  73.             }  
  74.             else {  
  75.                 $scope.msg = "Error : Something Wrong";  
  76.             }  
  77.         }, function (error) {  
  78.             $scope.msg = "Error : Something Wrong";  
  79.         })  
  80.   
  81.     }  
  82.   
  83. }]);   

Create HTML page

To add HTML page, right click on the project name > Add > HTML page.

AngularJS

ImportData.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title>.: Import Data with AngularJS :.</title>  
  5.     <meta charset="utf-8" />  
  6.   
  7.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  8.   
  9.   
  10. </head>  
  11. <body ng-app="app">  
  12.   
  13.     <div ng-controller="Ctrl" class="container" style="margin-top:50px;">  
  14.   
  15.   
  16.             <input type="file" name="file" class="form-control"  
  17.                    onchange="angular.element(this).scope().loadFile(this.files)" />  
  18.         <br/><br/>  
  19.             <input type="button" value="Import Data" class="btn btn-default"  
  20.                    ng-click="handleFile()" />  
  21.         <br/>  
  22.         <p ng-bind="msg"></p>  
  23.   
  24.     </div>  
  25.   
  26.     <!-- JS -->  
  27.     <script src="Scripts/angular.min.js"></script>  
  28.     <script src="Scripts/ImportData.js"></script>  
  29.   
  30.     <script src="Scripts/xlsx.full.min.js"></script>  
  31.     <script src="Scripts/jszip.js"></script>  
  32.   
  33.   
  34. </body>  
  35. </html>   

Note

Don’t forget to add the libraries given below in ImportData.html 

  1. <!-- JS -->  
  2.     <script src="Scripts/angular.min.js"></script>  
  3.     <script src="Scripts/ImportData.js"></script>  
  4.   
  5.     <script src="Scripts/xlsx.full.min.js"></script>  
  6.     <script src="Scripts/jszip.js"></script>   

Demo

Here, I have created an Excel file with the records given below.

AngularJS

Now, you can run your Application. Try to upload an Excel file, followed by clicking on import data button. Finally refresh your table from the database created previously and see the result, as shown below.
AngularJS

AngularJS

See also

  • http://jsfiddle.net/danielzen/utp7j/
  • https://github.com/SheetJS/js-xlsx

Happy coding.