How to Upload Excel File in Angularjs Using Mvc
Introduction
In this article, I volition demonstrate how to import Excel data into SQL Server using AngularJS in MVC5. I will use jQuery AJAX to think the data from the database and also use jQuery data table for sorting, searching and paging functionality.
Step 1Open SQL Server 2014 and create a database table to insert and call back the data.
- CREATE Tabular array [dbo].[StudentsList](
- [RollNumber] [int ] IDENTITY(grand,i) Not NULL ,
- [Student_Name] [nvarchar](50)Cypher ,
- [Hindi] [int ] NULL ,
- [English] [int ] NULL ,
- [Physics] [int ] NULL ,
- [Chemical science] [int ] Cipher ,
- [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 [ Principal ]
- Get
Screenshot for the database table
Stride 2Open Visual Studio 2015, click on New Project, and create an empty web application project.
Screenshot for creating new project i
After clicking on New Project, i window will appear. Select Spider web from the left console, choose ASP.NET Web Awarding, requite it a meaningful proper noun and click on OK.
Screenshot for creating new project ii
One more than window will appear; choose Empty check on MVC checkbox and click on OK.
Screenshot for creating new projection 3
Subsequently clicking on OK, the project will exist created with the name of ImportExcelDataAngularJS_Demo.
Pace 3Add together Entity Framework, right click on Models binder, select Add and and then select New Particular followed by a click on it.
Screenshot for calculation Entity Framework i
Later on clicking on New Detail, you will go a window. From there, select Data from the left console and choose ADO.Cyberspace Entity Information Model, give it a name as DBModels (this name is not mandatory; you tin give any name), then click on Add.
Screenshot for adding Entity Framework ii
Afterward y'all click on Add, a window wizard will open. Choose EF Designer from the database and click Next.
Screenshot for calculation Entity Framework 3
Afterward clicking on Next, a new window will appear. Cull New Connection.
Screenshot for calculation Entity Framework 4
Another window will announced. Add your server proper noun; 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 every bit you want, you tin modify the proper name of your connectedness below. It volition save connection in web config. Only click on Next.
Screenshot for adding Entity Framework vi
Afterwards clicking on NEXT another window volition appear. Choose database table proper name as shown in below screenshot then click on Finish. Entity framework will exist added and respective grade gets generated under Models folder.
Screenshot for adding Entity Framework 7
Screenshot for adding Entity Framework viii
Following form will be added.
- namespace ImportExcelDataAngularJS_Demo.Models
- {
- using Organisation;
- using Organisation.Collections.Generic;
- publicclass StudentsList
- {
- publicint RollNumber { get; set; }
- public cord Student_Name { get; set; }
- public Nullable<int> Hindi { get; set; }
- public Nullable<int> English { get; set up; }
- public Nullable<int> Physics { become; fix; }
- public Nullable<int> Chemistry { go; gear up; }
- public Nullable<int> Biology { get; fix; }
- public Nullable<int> Mathematics { get; set; }
- }
- }
Step 4Right click on Controllers folder select Add together then cull Controller. Every bit 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. Modify the name HomeController then click on Add. HomeController will be added under Controllers binder. As shown in the below screenshot.
Add the following namespace in controller
- using ImportExcelDataAngularJS_Demo.Models;
Consummate controller lawmaking.
- using ImportExcelDataAngularJS_Demo.Models;
- using System.Collections.Generic;
- using System.Linq;
- using Arrangement.Web.Mvc;
- namespace ImportExcelDataAngularJS_Demo.Controllers
- {
- publicclass HomeController : Controller
- {
- public ActionResult Alphabetize()
- {
- return View();
- }
- public ActionResult GetData()
- {
- using (DBModel db =new DBModel())
- {
- List<StudentsList> studentList = db.StudentsLists.ToList<StudentsList>();
- return Json(new { information = studentList }, JsonRequestBehavior.AllowGet);
- }
- }
- public ActionResult ImportData()
- {
- return View();
- }
- [HttpPost]
- public ActionResult ImportData(List<StudentsList> studentList)
- {
- bool status =simulated;
- if (ModelState.IsValid)
- {
- using (DBModel db =new DBModel())
- {
- foreach (var iin studentList)
- {
- db.StudentsLists.Add(i);
- }
- db.SaveChanges();
- status =true;
- }
- }
- returnnew JsonResult { Data =new { status = status } };
- }
- }
- }
Footstep 5
Right click on ImportData activeness method in controller. Add view. A window will appear with default ImportData name unchecked (utilize a Layout page) click on Add, every bit show in the below screenshot. View will be added in views binder nether Home folder with name Cavalcade.
Screenshot for adding view
Step 6
Click on Tools select NuGet Bundle Manager then choose Manage NuGet Packages for Solution click on information technology.
Screenshot for NuGet Package
After that a window volition announced cull 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.
Go along required bootstrap and jQuery file and delete remaining file if not using. Or you tin 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-crawly/4.vii.0/css/font-awesome.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-three.3.one.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.total.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.half-dozen.one/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": [
- {"information":"RollNumber" },
- {"data":"Student_Name" },
- {"data":"Hindi" },
- {"data":"English" },
- {"data":"Physics" },
- {"data":"Chemistry" },
- {"information":"Biology" },
- {"data":"Mathematics" }
- ]
- });
- });
- </script>
Footstep 8
Right click on scripts folder, select Add, and choose JavaScript File. Give name every bit ImportData.js. Write thescript to go information from database.
- var app = angular.module('MyApp', []);
- app.controller('MyController', ['$scope','$http',function ($scope, $http) {
- $scope.SelectedFileForUpload =aught;
- $telescopic.UploadFile =function (files) {
- $scope.$apply(function () {
- $scope.Message ="";
- $scope.SelectedFileForUpload = files[0];
- })
- }
- $telescopic.ParseExcelDataAndSave =role () {
- var file = $scope.SelectedFileForUpload;
- if (file) {
- var reader =new FileReader();
- reader.onload =function (east) {
- var data = east.target.result;
- var workbook = XLSX.read(data, { blazon:'binary' });
- var sheetName = workbook.SheetNames[0];
- var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
- if (excelData.length > 0) {
- $telescopic.SaveData(excelData);
- }
- else {
- $telescopic.Message ="No data found";
- }
- }
- reader.onerror =function (ex) {
- console.log(ex);
- }
- reader.readAsBinaryString(file);
- }
- }
- $scope.SaveData =part (excelData) {
- $http({
- method:"POST",
- url:"/Home/ImportData",
- data: JSON.stringify(excelData),
- headers: {
- 'Content-Blazon':'application/json'
- }
- }).then(role (data) {
- if (data.status) {
- $scope.Message = excelData.length +" record inserted";
- }
- else {
- $telescopic.Bulletin ="Failed";
- }
- },function (error) {
- $scope.Bulletin ="Error";
- })
- }
- }])
Step 9Design the view with HTML, cshtml and bootstrap 4 classes.
- <body ng-app="MyApp">
- <divclass="container py-four" ng-controller="MyController">
- <h5class="text-center text-uppercase">How to Import Excel Data into Sql Server Using Angular Jsin Mvc5</h5>
- <divgrade="card">
- <divclass="card-header bg-primary text-white">
- <h5>Students Event Listing</h5>
- </div>
- <divclass="carte-body">
- <button style="margin-bottom:10px;" type="push"form="btn btn-principal rounded-0" data-toggle="modal" data-target="#myModal">
- <iclass="fa fa-file-excel-o"></i> Upload Excel File
- </button>
- <divclass="modal" id="myModal">
- <divclass="modal-dialog">
- <divclass="modal-content">
- <divclass="modal-header">
- <h4class="modal-title">Upload Students Result</h4>
- <button type="button"class="close" data-dismiss="modal">×</button>
- </div>
- <divclass="modal-body">
- <divclass="col-md-12">
- <divclass="input-grouping">
- <divclass="custom-file">
- <input type="file" name="file"course="custom-file-input" onchange="angular.element(this).scope().UploadFile(this.files)" />
- <labelform="custom-file-characterization"for="inputGroupFile04">Choose file</label>
- </div>
- <divclass="input-group-append">
- <push buttoncourse="btn btn-outline-secondary" type="push" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcelDataAndSave()"><iclass="fa fa-upload"></i> Upload</button>
- </div>
- </div>
- <spanclass="text-success">
- {{Message}}
- </span>
- </div>
- </div>
- <divclass="modal-footer">
- <push button type="button"class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <table id="dataTable"grade="tabular array table-bordered table-striped">
- <thead>
- <tr>
- <th>Roll No.</thursday>
- <th>Name</th>
- <thursday>Hindi</thursday>
- <th>English</th>
- <th>Physics</th>
- <th>Chemistry</th>
- <th>Biology</th>
- <th>Mathematics</thursday>
- </tr>
- </thead>
- </tabular array>
- </div>
- </div>
- </div>
- </body>
Complete View code
- @{
- Layout =null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <championship>ImportData</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/four.vii.0/css/font-crawly.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-three.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.eight.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/athwart.js/1.six.one/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 blazon="text/javascript">
- $(document).ready(office () {
- $('#dataTable').DataTable({
- "ajax": {
- "url":"/Habitation/GetData",
- "type":"Go",
- "datatype":"json"
- },
- "columns": [
- {"information":"RollNumber" },
- {"data":"Student_Name" },
- {"data":"Hindi" },
- {"information":"English language" },
- {"data":"Physics" },
- {"data":"Chemistry" },
- {"data":"Biological science" },
- {"information":"Mathematics" }
- ]
- });
- });
- </script>
- </head>
- <body ng-app="MyApp">
- <divclass="container py-4" ng-controller="MyController">
- <h5grade="text-centre text-uppercase">How to Import Excel Information into Sql Server Using Angular Jsin Mvc5</h5>
- <divclass="card">
- <divclass="card-header bg-master text-white">
- <h5>Students Result List</h5>
- </div>
- <divclass="bill of fare-body">
- <button manner="margin-bottom:10px;" blazon="button"class="btn btn-primary rounded-0" data-toggle="modal" information-target="#myModal">
- <iclass="fa fa-file-excel-o"></i> Upload Excel File
- </button>
- <divgrade="modal" id="myModal">
- <divgrade="modal-dialog">
- <divclass="modal-content">
- <divgrade="modal-header">
- <h4course="modal-title">Upload Students Result</h4>
- <button type="button"class="close" data-dismiss="modal">×</push button>
- </div>
- <divgrade="modal-body">
- <divform="col-md-12">
- <divclass="input-group">
- <divclass="custom-file">
- <input type="file" name="file"class="custom-file-input" onchange="angular.element(this).scope().UploadFile(this.files)" />
- <characterizationcourse="custom-file-label"for="inputGroupFile04">Cull file</label>
- </div>
- <divclass="input-grouping-append">
- <buttongrade="btn btn-outline-secondary" type="push" ng-disabled="!SelectedFileForUpload" ng-click="ParseExcelDataAndSave()"><iclass="fa fa-upload"></i> Upload</button>
- </div>
- </div>
- <spanclass="text-success">
- {{Message}}
- </bridge>
- </div>
- </div>
- <divclass="modal-footer">
- <push blazon="button"class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <table id="dataTable"course="table tabular array-bordered table-striped">
- <thead>
- <tr>
- <th>Coil No.</thursday>
- <th>Proper name</th>
- <th>Hindi</th>
- <th>English</th>
- <th>Physics</th>
- <th>Chemistry</th>
- <th>Biology</th>
- <thursday>Mathematics</thursday>
- </tr>
- </thead>
- </tabular array>
- </div>
- </div>
- </div>
- </body>
- </html>
Step 10
Run the project by pressing Ctrl+F5.
Screenshot 1
Screenshot two
Screenshot iii
Screenshot four
Conclusion
In this article, I have explained how to upload Excel data into SQL Server database table using Angular with MVC5 step by stride. I hope it will exist useful for you.
Source: https://www.c-sharpcorner.com/article/how-to-import-excel-data-into-sql-server-using-angular-in-mvc-5/
0 Response to "How to Upload Excel File in Angularjs Using Mvc"
Post a Comment