In this blog, a lot of things have been covered through a web application.
- Read Excel through EPPlus Library through MVC Application.
- Upload Bulk Excel Data into a database in single DB Call through ADO.NET.
- Capture a table's column values through a trigger in a different table.
Here, I am providing a basic application which has the functionality to upload an Excel sheet and import that sheet's data into a database table. If the Excel data is having any new record, then it will insert that data into the table, otherwise it will update that existing data into the corresponding table and capture the log with new and old values in a different table through a trigger.
There are few things that need to be done before running the application.
- Download the attached script files.
- Run all scripts in given steps on your database server which is attached in the zip format.
- Scripts object including (Table, Trigger, Table Type, Store Procedure).
- Change the respective data source name, username, and password in the webconfig file.
<add name="devConString" connectionString="Data Source=DataSourceName;Initial Catalog=Databasename;User ID=UserID;Password=Password" />
- Upload the Excel in the given format.
- Read Excel file. I am using EPPLUS Library that you can download from NuGet.
- Create a new fresh Web MVC application and copy and paste the below home controller code, index code, and change the connection string accordingly in the webconfig file.
Below are the code details for Home Controller, Index Page, and webconfig file.
- using CaptureLog.Models;
- using Microsoft.SqlServer.Server;
- using OfficeOpenXml;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace UploadReauthReport.Controllers
- {
- public class HomeController : Controller
- {
-
-
-
- public const string PROC_INSERT_Employee_REPORT_RECORDS = "Orc_Proc_HRReportData";
-
-
-
-
- public const string PARAM_Employee_REPORT_RECORDS = "@HRReportDataModel";
- public ActionResult Index()
- {
- return View();
- }
-
-
-
-
-
-
- public List<EmployeeDataModel> ReadEmployeeExcelData(HttpPostedFileBase FileUpload)
- {
- List<EmployeeDataModel> employeeDataModel = new List<EmployeeDataModel>();
- if (FileUpload != null)
- {
- string filename = FileUpload.FileName;
- using (var package = new ExcelPackage(FileUpload.InputStream))
- {
- var currentSheet = package.Workbook.Worksheets;
- var workSheet = currentSheet.First();
- var noOfCol = workSheet.Dimension.End.Column;
- var noOfRow = workSheet.Dimension.End.Row;
- for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
- {
-
- employeeDataModel.Add(new EmployeeDataModel
- {
- Name = Convert.ToString(workSheet.Cells[rowIterator, 1].Value).Trim(),
- Address = Convert.ToString(workSheet.Cells[rowIterator, 2].Value).Trim(),
- Manager = Convert.ToString(workSheet.Cells[rowIterator, 3].Value).Trim(),
- });
- }
- }
-
- return employeeDataModel;
-
- }
- return employeeDataModel;
- }
-
-
-
-
-
-
- public ActionResult UploadEmployeeData(HttpPostedFileBase file)
- {
- try
- {
- if (file != null && file.ContentLength > 0)
- {
- string fileExt = string.Empty;
- string _FileName = Path.GetFileName(file.FileName);
- fileExt = Path.GetExtension(_FileName);
- if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- {
- List<EmployeeDataModel> employeeDataModel = ReadEmployeeExcelData(file);
- if (employeeDataModel != null && employeeDataModel.Count > 0)
- {
- InsertEmployeeData(employeeDataModel);
- }
- ViewBag.Message = string.Format("{0} records uploaded successfully.", employeeDataModel.Count);
- ViewBag.IsSuccess = true;
- return View("Index");
- }
- else
- {
- ViewBag.IsSuccess = false;
- ViewBag.Message = "Please choose Excel file";
- return View("Index");
- }
- }
- else
- {
- ViewBag.IsSuccess = false;
- ViewBag.Message = "No file to import in system";
- return View("Index");
- }
- }
- catch (Exception ex)
- {
- ViewBag.IsSuccess = false;
- ViewBag.Message = ex.Message;
- return View("Index");
- }
- }
-
-
-
-
-
-
- private SqlConnection CreateSqlConnection()
- {
- #if DEBUG
- string strConnString = ConfigurationManager.ConnectionStrings["devConString"].ConnectionString;
- return new SqlConnection(strConnString);
- #else
-
- #endif
- }
-
-
-
-
-
-
-
- private List<SqlDataRecord> ConvertEmployeeResponseToUT(List<EmployeeDataModel> records)
- {
- var columns = new SqlMetaData[3];
- columns[0] = new SqlMetaData("Name", SqlDbType.VarChar, 4000);
- columns[1] = new SqlMetaData("Address", SqlDbType.VarChar, 4000);
- columns[2] = new SqlMetaData("Manager", SqlDbType.VarChar, 4000);
- List<SqlDataRecord> dataRecords = new List<SqlDataRecord>();
- foreach (var item in records)
- {
- SqlDataRecord record = new SqlDataRecord(columns);
- record.SetString(0, item.Name);
- record.SetString(1, item.Address);
- record.SetString(2, item.Manager);
- dataRecords.Add(record);
- }
- return dataRecords;
- }
-
-
-
-
-
-
-
- private void InsertEmployeeData(List<EmployeeDataModel> records)
- {
-
- if (records.Count > 0)
- {
- List<SqlDataRecord> recordsDS = ConvertEmployeeResponseToUT(records);
- SqlConnection conn = this.CreateSqlConnection();
- SqlCommand cmd = new SqlCommand();
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.CommandText = PROC_INSERT_Employee_REPORT_RECORDS;
- cmd.Parameters.Add(PARAM_Employee_REPORT_RECORDS, SqlDbType.Structured).Value = recordsDS;
- cmd.Connection = conn;
- try
- {
- conn.Open();
- cmd.ExecuteNonQuery();
- }
- finally
- {
- conn.Close();
- conn.Dispose();
- }
- }
- }
- }
- }
Employee Data Model Class
Read data from Excel and convert into this model class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace CaptureLog.Models
- {
- public class EmployeeDataModel
- {
- public string Name { get; set; }
- public string Address { get; set; }
- public string Manager { get; set; }
- }
- }
Below is the Index page Razor Control code.
- @{
- ViewBag.Title = "Capture Logging";
- }
-
- <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" />
- <br />
- <div class="form-group">
- @{
- if (ViewBag.IsSuccess != null && ViewBag.IsSuccess)
- {
- <div class="alert alert-success">
- <strong>Success !</strong> @ViewBag.Message
- </div>
- }
- else if (ViewBag.IsSuccess != null)
- {
- <div class="alert alert-danger" role="alert">
- <strong>Error !</strong> @ViewBag.Message
- </div>
- }
- }
-
- </div>
- <br />
-
- <div class="container">
- <div class="row">
- <div class="col-sm-4">
- <div class="form-group">
- <div class="container">
- <div class="panel-group">
- <div class="panel panel-default">
- <div class="panel-heading">Bulk Capture Log</div>
- <div class="panel-body">
- <div class="row">
- @using (Html.BeginForm("UploadEmployeeData", "Home", FormMethod.Post, new { enctype = "multipart/form-data", @class = "width100 form-inline" }))
- {
- <div class="form-group required">
- <label class="control-label" for="email">Upload:</label>
- @Html.TextBox("file", "", new { type = "file", @class = "form-control" })
- </div>
-
- <div class="form-group">
- <input type="submit" value="Import File" class="form-control btn btn-primary disablebutton btnSubmit" />
- </div>
-
- }
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="col-sm-4">
-
- </div>
- <div class="col-sm-4">
-
- </div>
- </div>
- </div>
Web Config File Code
- <?xml version="1.0" encoding="utf-8"?>
- <!--
- For more information on how to configure your ASP.NET application, please visit
- https://go.microsoft.com/fwlink/?LinkId=301880
- -->
- <configuration>
- <appSettings>
- <add key="webpages:Version" value="3.0.0.0" />
- <add key="webpages:Enabled" value="false" />
- <add key="ClientValidationEnabled" value="true" />
- <add key="UnobtrusiveJavaScriptEnabled" value="true" />
- </appSettings>
- <system.web>
- <compilation debug="true" targetFramework="4.6.1" />
- <httpRuntime targetFramework="4.6.1" />
- </system.web>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
- <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
- <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
- <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
- <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
- <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
- <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
- <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
- <bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
- <system.webServer>
- <modules>
- <remove name="TelemetryCorrelationHttpModule" />
- <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
- </modules>
- </system.webServer>
- <connectionStrings>
- <add name="devConString" connectionString="Data Source=ChangeTheDataSourceName;Initial Catalog=DatabaseName;User ID=userName;Password=Password" />
- </connectionStrings>
- <system.codedom>
- <compilers>
- <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
- <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
- </compilers>
- </system.codedom>
- </configuration>