import data from excel to sql server programmatically Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Wed, 21 Dec 2022 13:45:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 import data from excel to sql server programmatically Archives - Tech Insights 32 32 230003556 How to Import data from Excel File into Database in Asp.net Core MVC https://reactconf.org/how-to-import-data-from-excel-file-into-database-in-asp-net-core-mvc/ https://reactconf.org/how-to-import-data-from-excel-file-into-database-in-asp-net-core-mvc/#respond Wed, 21 Dec 2022 13:45:29 +0000 https://labpys.com/?p=562 In this article, we will learn how to Import Excel File into Database in Asp.net Core MVC . In previous article we had discussed How to Upload multiple files using …

The post How to Import data from Excel File into Database in Asp.net Core MVC appeared first on Tech Insights.

]]>
In this article, we will learn how to Import Excel File into Database in Asp.net Core MVC . In previous article we had discussed How to Upload multiple files using Asp.Net Core MVC C#.

SqlBulkCopy – Class can be used to write data only to SQL Server table. However SqlBulkCopy Class insert data from one source to another as long as the data can be loaded to a DataTable instance , hence all rows from excel sheet data can be easily read and inserted (import) using the SqlBulkCopy class.

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here
  • Sql-Server

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Enter  project name and click create.

Install NuGet Packages

  • Microsoft Entity Framework Core Sql Server.
  • Microsoft Entity Framework Core Tools
  • System.Data.OleDb

Configure appsettings.json

There are two connection string one is SQL Server and another one is excel .

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "sqlconnection": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true",
    "excelconnection":"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"
    
  },
  "AllowedHosts": "*"
}

Create Model

Create Model class and DbContext Class.

//Customer.cs

using System.ComponentModel.DataAnnotations;

namespace Asp.netcore_Tutorials.Models
{
    public class Customer
    {
        [Key]

        public int id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string job { get; set; }
        public float amount { get; set; }
        public DateTime tdate { get; set; }
    }
}
//CustDbcontext.cs
using Microsoft.EntityFrameworkCore;

namespace Asp.netcore_Tutorials.Models
{
    public class CustDbcontext :DbContext 
    {

        public CustDbcontext(DbContextOptions<CustDbcontext> options):base(options)
        {

        }

        public virtual DbSet<Customer> Customers { get; set; }
    }
}

Create Interface and Concrete Class

Interface ICustomer.cs

using System.Data;

namespace Asp.netcore_Tutorials.Repository
{
    public interface ICustomer
    {
        string Documentupload(IFormFile formFile);
        DataTable CustomerDataTable(string path);
        void ImportCustomer(DataTable customer);
    } 
}

Concrete Class Customerdetail.cs

using Microsoft.AspNetCore.Http;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;

namespace Asp.netcore_Tutorials.Repository
{
    public class CustomerDetail : ICustomer
    {
        private IConfiguration _configuration;
        private IWebHostEnvironment _environment;
        public CustomerDetail(IConfiguration configuration, IWebHostEnvironment environment)
        {
            _configuration = configuration;
            _environment = environment;
        }
        public DataTable CustomerDataTable(string path)
        {
            var constr = _configuration.GetConnectionString("excelconnection");
            DataTable datatable = new DataTable();

            constr = string.Format(constr, path);

            using (OleDbConnection excelconn = new OleDbConnection(constr))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    using (OleDbDataAdapter adapterexcel = new OleDbDataAdapter())
                    {

                        excelconn.Open();
                        cmd.Connection = excelconn;
                        DataTable excelschema;
                        excelschema = excelconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        var sheetname = excelschema.Rows[0]["Table_Name"].ToString();
                        excelconn.Close();

                        excelconn.Open();
                        cmd.CommandText = "SELECT * From [" + sheetname + "]";
                        adapterexcel.SelectCommand = cmd;
                        adapterexcel.Fill(datatable);
                        excelconn.Close();

                    }
                }

            }

            return datatable;
        }

        public string Documentupload(IFormFile fromFiles)
        {
            string uploadpath = _environment.WebRootPath;
            string dest_path = Path.Combine(uploadpath, "uploaded_doc");

            if (!Directory.Exists(dest_path))
            {
                Directory.CreateDirectory(dest_path);
            }
            string sourcefile = Path.GetFileName(fromFiles.FileName);
            string path = Path.Combine(dest_path, sourcefile);

            using (FileStream filestream = new FileStream(path, FileMode.Create))
            {
                fromFiles.CopyTo(filestream);
            }
            return path;
        }

        public void ImportCustomer(DataTable customer)
        {
            
            var sqlconn = _configuration.GetConnectionString("sqlconnection");
            using (SqlConnection scon = new SqlConnection(sqlconn))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(scon))
                {
                    sqlBulkCopy.DestinationTableName = "Customers";


                    sqlBulkCopy.ColumnMappings.Add("FirstName", "firstName");
                    sqlBulkCopy.ColumnMappings.Add("LastName", "lastName");
                    sqlBulkCopy.ColumnMappings.Add("job", "job");
                    sqlBulkCopy.ColumnMappings.Add("amount", "amount");
                    sqlBulkCopy.ColumnMappings.Add("hiredate", "tdate");

                    scon.Open();
                    sqlBulkCopy.WriteToServer(customer);
                    scon.Close();
                }

            }
        }
    } 
}

Configure Program.cs

using Asp.netcore_Tutorials.Models;
using Asp.netcore_Tutorials.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();


builder.Services.AddDbContext<CustDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection")));  
builder.Services.AddScoped<ICustomer,CustomerDetail>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Migration

Add-Migration 'Initial-Create'
Update-Database

Create Controller

using Asp.netcore_Tutorials.Repository;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace Asp.netcore_Tutorials.Controllers
{
    public class ImportExcelSqlController : Controller
    {

        private IWebHostEnvironment _environment;
        private readonly ICustomer _customer;
      //  private IConfiguration _configuration;
        public ImportExcelSqlController(IWebHostEnvironment environment,ICustomer customer)
        {
            _environment = environment;
            _customer = customer;            
        }  

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public IActionResult Index(IFormFile fromFiles)
        {
            string path = _customer.Documentupload(fromFiles);
            DataTable dt = _customer.CustomerDataTable(path);
            _customer.ImportCustomer(dt); 
            return View();
        } 
    }
}

Customize View Index

@{
    ViewData["Title"] = "Home Page";
}

<div class="row">
    <div class="col-5">

        <form method="post" enctype="multipart/form-data" asp-controller="ImportExcelSql" asp-action="Index">
            <div class="form-group">
                <div class="col-md-10">
                    <h3>Upload File</h3>
                    <input class="form-control" name="fromFiles" multiple="multiple" type="file" />
                </div>
            </div>
            <br />
            <div class="form-group">
                <div class="col-md-10">

                    <input class="btn btn-primary" type="submit" value="Upload File" />

                </div>
            </div>
        </form>        
    </div>
</div>

The post How to Import data from Excel File into Database in Asp.net Core MVC appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-import-data-from-excel-file-into-database-in-asp-net-core-mvc/feed/ 0 562