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
Create a table
- USE [DbEmployee]
- GO
-
- /****** Object: Table [dbo].[EmployeeTable] Script Date: 3/25/2017 8:23:51 AM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[EmployeeTable](
- [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [varchar](50) NULL,
- [LastName] [varchar](50) NULL,
- [Gender] [varchar](50) NULL,
- [Designation] [nchar](10) NULL,
- [Salary] [int] NULL,
- [City] [varchar](50) NULL,
- [Country] [varchar](50) NULL,
- CONSTRAINT [PK_EmployeeTable] PRIMARY KEY CLUSTERED
- (
- [EmployeeID] 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
-
- SET ANSI_PADDING OFF
- GO
After creating the table, you can add some records. as shown below.
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.
Now, new dialog will pop up to select the template. We are going to choose Web API template and click OK button.
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.
In this level, we are going to choose EF Designer from the database, as show below.
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.
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.
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.
Enter Controller name (‘EmployeeController’).
EmployeeController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Web.Http.Description;
-
- namespace ExcelToDB.Controllers
- {
- [RoutePrefix("api/Employee")]
- public class EmployeeController : ApiController
- {
-
- DbEmployeeEntities db = new DbEmployeeEntities();
-
-
- [Route("Save")]
- [HttpPost]
- [ResponseType(typeof(void))]
- public IHttpActionResult Save(List<EmployeeTable> employeeList)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
-
- foreach(var data in employeeList)
- {
- db.EmployeeTables.Add(data);
- }
- db.SaveChanges();
-
- return StatusCode(HttpStatusCode.OK);
-
- }
-
- }
- }
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.
ImportData.js
- var app = angular.module('app', []);
-
- app.controller('Ctrl', ['$scope', '$http', function ($scope, $http) {
-
- $scope.selectedFile = null;
- $scope.msg = "";
-
-
- $scope.loadFile = function (files) {
-
- $scope.$apply(function () {
-
- $scope.selectedFile = files[0];
-
- })
-
- }
-
- $scope.handleFile = function () {
-
- var file = $scope.selectedFile;
-
- if (file) {
-
- var reader = new FileReader();
-
- reader.onload = function (e) {
-
- var data = e.target.result;
-
- var workbook = XLSX.read(data, { type: 'binary' });
-
- var first_sheet_name = workbook.SheetNames[0];
-
- var dataObjects = XLSX.utils.sheet_to_json(workbook.Sheets[first_sheet_name]);
-
-
-
- if (dataObjects.length > 0) {
-
-
- $scope.save(dataObjects);
-
-
- } else {
- $scope.msg = "Error : Something Wrong !";
- }
-
- }
-
- reader.onerror = function (ex) {
-
- }
-
- reader.readAsBinaryString(file);
- }
- }
-
-
- $scope.save = function (data) {
-
- $http({
- method: "POST",
- url: "api/Employee/Save",
- data: JSON.stringify(data),
- headers: {
- 'Content-Type': 'application/json'
- }
-
- }).then(function (data) {
- if (data.status) {
- $scope.msg = "Data has been inserted ! ";
- }
- else {
- $scope.msg = "Error : Something Wrong";
- }
- }, function (error) {
- $scope.msg = "Error : Something Wrong";
- })
-
- }
-
- }]);
Create HTML page
To add HTML page, right click on the project name > Add > HTML page.
ImportData.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>.: Import Data with AngularJS :.</title>
- <meta charset="utf-8" />
-
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
-
-
- </head>
- <body ng-app="app">
-
- <div ng-controller="Ctrl" class="container" style="margin-top:50px;">
-
-
- <input type="file" name="file" class="form-control"
- onchange="angular.element(this).scope().loadFile(this.files)" />
- <br/><br/>
- <input type="button" value="Import Data" class="btn btn-default"
- ng-click="handleFile()" />
- <br/>
- <p ng-bind="msg"></p>
-
- </div>
-
- <!-- JS -->
- <script src="Scripts/angular.min.js"></script>
- <script src="Scripts/ImportData.js"></script>
-
- <script src="Scripts/xlsx.full.min.js"></script>
- <script src="Scripts/jszip.js"></script>
-
-
- </body>
- </html>
Note
Don’t forget to add the libraries given below in ImportData.html
- <!-- JS -->
- <script src="Scripts/angular.min.js"></script>
- <script src="Scripts/ImportData.js"></script>
-
- <script src="Scripts/xlsx.full.min.js"></script>
- <script src="Scripts/jszip.js"></script>
Demo
Here, I have created an Excel file with the records given below.
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.
See also
- http://jsfiddle.net/danielzen/utp7j/
- https://github.com/SheetJS/js-xlsx
Happy coding.