I will show you how to connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then insert it into the database table.
To begin with, we will create an ExcelToDatabase in Home Controller which returns a View. This method will return a View from where we have to upload the excel file. Now we will create another method ExcelToDatabase. Now if we make a get request then ExcelToDatabase will be called and for post request, ExcelToDatabase will be called. The following is the code to read excel files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace ExcelReadData
{
public class HomeController : Controller
{
// GET: ClonePanel
public ActionResult ExcelToDatabase()
{
return View();
}
[HttpPost]
public ActionResult ExcelToDatabase()
{
bool result = false;
ViewBag.data = null;
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
string query = null;
string connString = "";
string[] validFileTypes = { ".xls", ".xlsx" };
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
if (!Directory.Exists(path1))
{
Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
}
if (validFileTypes.Contains(extension))
{
if (System.IO.File.Exists(path1))
{ System.IO.File.Delete(path1); }
Request.Files["FileUpload1"].SaveAs(path1);
//Connection String to Excel Workbook
if (extension.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
result = Service.ImportExceltoDatabase(path1, connString, userId);
}
else if (extension.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
result = Service.ImportExceltoDatabase(path1, connString,userId);
}
}
else
{
ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format";
}
}
if (result)
{
ViewBag.data = "Data Import Successfully from excel to database.";
}
else
{
ViewBag.data = "there is some issue while importing the Data.";
}
return View();
}
}
}
Join the conversation! Your thoughts help the community grow.