Introduction
In this article, I will demonstrate how to import Excel data into SQL Server using AngularJS in MVC5. I will use jQuery AJAX to retrieve the data from the database and also use jQuery data table for sorting, searching and paging functionality.
Step 1
Open SQL Server 2014 and create a database table to insert and retrieve the data.
- CREATE TABLE [dbo].[StudentsList](
- [RollNumber] [int] IDENTITY(1000,1) NOT NULL,
- [Student_Name] [nvarchar](50) NULL,
- [Hindi] [int] NULL,
- [English] [int] NULL,
- [Physics] [int] NULL,
- [Chemistry] [int] NULL,
- [Biology] [int] NULL,
- [Mathematics] [int] NULL,
- CONSTRAINT [PK_StudentsList] PRIMARY KEY CLUSTERED
- (
- [RollNumber] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Screenshot for the database table
Step 2
Open Visual Studio 2015, click on New Project, and create an empty web application project.
Screenshot for creating new project 1
After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give it a meaningful name and click on OK.
Screenshot for creating new project 2
One more window will appear; choose Empty check on MVC checkbox and click on OK.
Screenshot for creating new project 3
After clicking on OK, the project will be created with the name of ImportExcelDataAngularJS_Demo.
Step 3
Add Entity Framework, right click on Models folder, select Add and then select New Item followed by a click on it.
Screenshot for adding Entity Framework 1
After clicking on New Item, you will get a window. From there, select Data from the left panel and choose ADO.NET Entity Data Model, give it a name as DBModels (this name is not mandatory; you can give any name), then click on Add.
Screenshot for adding Entity Framework 2
After you click on Add, a window wizard will open. Choose EF Designer from the database and click Next.
Screenshot for adding Entity Framework 3
After clicking on Next, a new window will appear. Choose New Connection.
Screenshot for adding Entity Framework 4
Another window will appear. Add your server name; if it is local then enter dot (.). Choose your database and click on OK.
Screenshot for adding Entity Framework 5
Connection will get added. If you wish to save connection as you want, you can change the name of your connection below. It will save connection in web config. Just click on Next.
Screenshot for adding Entity Framework 6
After clicking on NEXT another window will appear. Choose database table name as shown in below screenshot then click on Finish. Entity framework will be added and respective class gets generated under Models folder.
Screenshot for adding Entity Framework 7
Screenshot for adding Entity Framework 8
Following class will be added.
- namespace ImportExcelDataAngularJS_Demo.Models
- {
- using System;
- using System.Collections.Generic;
-
- public class StudentsList
- {
- public int RollNumber { get; set; }
- public string Student_Name { get; set; }
- public Nullable<int> Hindi { get; set; }
- public Nullable<int> English { get; set; }
- public Nullable<int> Physics { get; set; }
- public Nullable<int> Chemistry { get; set; }
- public Nullable<int> Biology { get; set; }
- public Nullable<int> Mathematics { get; set; }
- }
- }
Step 4
Right click on Controllers folder select Add then choose Controller. As shown in below screenshot.
After click on controller a window will appear choose MVC5 Controller-Empty click on Add.
After clicking on Add another window will appear with DefaultController. Change the name HomeController then click on Add. HomeController will be added under Controllers folder. As shown in the below screenshot.
Add the following namespace in controller
- using ImportExcelDataAngularJS_Demo.Models;
Complete controller code.
- using ImportExcelDataAngularJS_Demo.Models;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Mvc;
-
- namespace ImportExcelDataAngularJS_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult GetData()
- {
- using (DBModel db = new DBModel())
- {
- List<StudentsList> studentList = db.StudentsLists.ToList<StudentsList>();
- return Json(new { data = studentList }, JsonRequestBehavior.AllowGet);
- }
- }
- public ActionResult ImportData()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult ImportData(List<StudentsList> studentList)
- {
- bool status = false;
- if (ModelState.IsValid)
- {
- using (DBModel db = new DBModel())
- {
- foreach (var i in studentList)
- {
- db.StudentsLists.Add(i);
- }
- db.SaveChanges();
- status = true;
- }
- }
- return new JsonResult { Data = new { status = status } };
- }
- }
- }
Step 5
Right click on ImportData action method in controller. Add view. A window will appear with default ImportData name unchecked (use a Layout page) click on Add, as show in the below screenshot. View will be added in views folder under Home folder with name Column.
Screenshot for adding view
Step 6
Click on Tools select NuGet Package Manager then choose Manage NuGet Packages for Solution click on it.
Screenshot for NuGet Package
After that a window will appear choose Browse type bootstrap and install package in project.
Similarly type JQuery and install latest version of JQuery package in project and jquery validation file from NuGet then close NuGet Solution.
Keep required bootstrap and jQuery file and delete remaining file if not using. Or you can download and add it in the project.
Step 7
Add required script and style in head section of view.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
- <script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
- <script src="~/scripts/ImportData.js"></script>
- <link href="~/Content/dataTables.bootstrap4.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery.dataTables.min.js"></script>
- <script src="~/scripts/dataTables.bootstrap4.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $('#dataTable').DataTable({
- "ajax": {
- "url": "/Home/GetData",
- "type": "GET",
- "datatype": "json"
- },
- "columns": [
- { "data": "RollNumber" },
- { "data": "Student_Name" },
- { "data": "Hindi" },
- { "data": "English" },
- { "data": "Physics" },
- { "data": "Chemistry" },
- { "data": "Biology" },
- { "data": "Mathematics" }
-
- ]
- });
- });
- </script>
Step 8
Right click on scripts folder, select Add, and choose JavaScript File. Give name as ImportData.js. Write thescript to get data from database.
- var app = angular.module('MyApp', []);
- app.controller('MyController', ['$scope', '$http', function ($scope, $http) {
- $scope.SelectedFileForUpload = null;
- $scope.UploadFile = function (files) {
- $scope.$apply(function () {
- $scope.Message = "";
- $scope.SelectedFileForUpload = files[0];
- })
- }
-
- $scope.ParseExcelDataAndSave = function () {
- var file = $scope.SelectedFileForUpload;
- if (file) {
- var reader = new FileReader();
- reader.onload = function (e) {
- var data = e.target.result;
-
- var workbook = XLSX.read(data, { type: 'binary' });
- var sheetName = workbook.SheetNames[0];
- var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
- if (excelData.length > 0) {
-
- $scope.SaveData(excelData);
- }
- else {
- $scope.Message = "No data found";
- }
- }
- reader.onerror = function (ex) {
- console.log(ex);
- }
-
- reader.readAsBinaryString(file);
- }
- }
-
- $scope.SaveData = function (excelData) {
- $http({
- method: "POST",
- url: "/Home/ImportData",
- data: JSON.stringify(excelData),
- headers: {
- 'Content-Type': 'application/json'
- }
- }).then(function (data) {
- if (data.status) {
- $scope.Message = excelData.length + " record inserted";
- }
- else {
- $scope.Message = "Failed";
- }
- }, function (error) {
- $scope.Message = "Error";
- })
- }
- }])
Step 9
Design the view with HTML, cshtml and bootstrap 4 classes.
- <body ng-app="MyApp">
- <div class="container py-4" ng-controller="MyController">
- <h5 class="text-center text-uppercase">How to Import Excel Data into Sql Server Using Angular Js in Mvc5</h5>
- <div class="card">
- <div class="card-header bg-primary text-white">
- <h5>Students Result List</h5>
- </div>
- <div class="card-body">
- <button style="margin-bottom:10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#myModal">
- <i class="fa fa-file-excel-o"></i> Upload Excel File
- </button>
- <div class="modal" id="myModal">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">Upload Students Result</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="col-md-12">
- <div class="input-group">
- <div class="custom-file">
- <input type="file" name="file" class="custom-file-input" onchange="angular.element(this).scope().UploadFile(this.files)" />
- <label class="custom-file-label" for="inputGroupFile04">Choose file</label>
- </div>
- <div class="input-group-append">
- <button class="btn btn-outline-secondary" type="button" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcelDataAndSave()"><i class="fa fa-upload"></i> Upload</button>
- </div>
- </div>
- <span class="text-success">
- {{Message}}
- </span>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <table id="dataTable" class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Roll No.</th>
- <th>Name</th>
- <th>Hindi</th>
- <th>English</th>
- <th>Physics</th>
- <th>Chemistry</th>
- <th>Biology</th>
- <th>Mathematics</th>
- </tr>
- </thead>
- </table>
- </div>
- </div>
- </div>
- </body>
Complete View code
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>ImportData</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
- <script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
- <script src="~/scripts/ImportData.js"></script>
- <link href="~/Content/dataTables.bootstrap4.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery.dataTables.min.js"></script>
- <script src="~/scripts/dataTables.bootstrap4.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $('#dataTable').DataTable({
- "ajax": {
- "url": "/Home/GetData",
- "type": "GET",
- "datatype": "json"
- },
- "columns": [
- { "data": "RollNumber" },
- { "data": "Student_Name" },
- { "data": "Hindi" },
- { "data": "English" },
- { "data": "Physics" },
- { "data": "Chemistry" },
- { "data": "Biology" },
- { "data": "Mathematics" }
-
- ]
- });
- });
- </script>
- </head>
- <body ng-app="MyApp">
- <div class="container py-4" ng-controller="MyController">
- <h5 class="text-center text-uppercase">How to Import Excel Data into Sql Server Using Angular Js in Mvc5</h5>
- <div class="card">
- <div class="card-header bg-primary text-white">
- <h5>Students Result List</h5>
- </div>
- <div class="card-body">
- <button style="margin-bottom:10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#myModal">
- <i class="fa fa-file-excel-o"></i> Upload Excel File
- </button>
- <div class="modal" id="myModal">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">Upload Students Result</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="col-md-12">
- <div class="input-group">
- <div class="custom-file">
- <input type="file" name="file" class="custom-file-input" onchange="angular.element(this).scope().UploadFile(this.files)" />
- <label class="custom-file-label" for="inputGroupFile04">Choose file</label>
- </div>
- <div class="input-group-append">
- <button class="btn btn-outline-secondary" type="button" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcelDataAndSave()"><i class="fa fa-upload"></i> Upload</button>
- </div>
- </div>
- <span class="text-success">
- {{Message}}
- </span>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <table id="dataTable" class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Roll No.</th>
- <th>Name</th>
- <th>Hindi</th>
- <th>English</th>
- <th>Physics</th>
- <th>Chemistry</th>
- <th>Biology</th>
- <th>Mathematics</th>
- </tr>
- </thead>
- </table>
- </div>
- </div>
- </div>
- </body>
- </html>
Step 10
Run the project by pressing Ctrl+F5.
Screenshot 1
Screenshot 2
Screenshot 3
Screenshot 4
Conclusion
In this article, I have explained how to upload Excel data into SQL Server database table using Angular with MVC5 step by step. I hope it will be useful for you.