Code2night
  • Home
  • Guest Posts
  • Tutorial
  • Languages
    • Angular
    • C
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
  • Register
  • Login
  1. Home
  2. Blogpost

Import Excel in Asp.net MVC using OLE DB

Date- Jun 23,2022

9950

Free Download Pay & Download
OLE DB Aspnet MVC

Hello guys and welcome to Code2Night, sometimes we need to import Excel in Asp.net MVC using OLE DB. So we will use OLE DB Connection for that as that is really fast and effective while reading large Excel files. You can check the steps on using that with the asp.net MVC project.

OLE DB

It is a Microsoft technology for access to data. It actually works with Microsoft Access Engine to read Excel or CSV files.

So, for reading Excel data from xlsx file, we will follow these steps.

1. First of all create a new asp.net MVC application and add a view with Html Form and add one input type file control on it along with a button to save the file

@using (Html.BeginForm("ImportExcelFile", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <div class="container mt-5" style="margin-top:10px;">
        <input type="file" name="file" />
        <br />
        <input type="submit" value="save" />
    </div>
}

So, we have here added a file-upload control on the view and a button for saving the file which we will read data from.

Import Excel

Now after adding the form we will go to the controller and add code for saving the selected file and then reading the data from data Excel file.

So, now take one controller with the name "Home" as we have mentioned in the beginning form. And add an action named "ImportExcelFile". You can copy that from here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace Export.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            
            return View();
        }

        public ActionResult ImportExcelFile(HttpPostedFileBase file)
        {
            string lsconnStr = string.Empty;
            DataTable dt = new DataTable();
            OleDbCommand command = null;
            var lsFilePath = Server.MapPath("/Content/TestFile"+DateTime.Now.ToString("ss")+".xlsx");
            file.SaveAs(lsFilePath);
            string lsFileExt = Path.GetExtension(lsFilePath);
           
            string errorMessage = "";
            string hdr = "Yes";
            int n_rows = 0;

            try
            {

                if (lsFileExt == ".xlsx")

                    lsconnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lsFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=" + hdr + ";IMEX=1;MAXSCANROWS=0'";
                else if (lsFileExt == ".xls")
                    lsconnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lsFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=" + hdr + ";IMEX=1;MAXSCANROWS=0'";
                else
                {
                    errorMessage = "Invalid file for import data. Allow only .xlsx.";
                }
                string s_excel_sql = string.Empty;
                OleDbConnection conn = new OleDbConnection(lsconnStr);
                conn.Open();
                DataTable excelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                string s_table = string.Empty;
                foreach (DataRow row in excelSchema.Rows)
                {
                    if (!row["TABLE_NAME"].ToString().Contains("FilterDatabase"))
                    {
                        if (!string.IsNullOrEmpty(s_table))
                        {
                            errorMessage = "Excel File contains multiple sheets. Please Upload Excel File with single Sheet.";

                        }
                        s_table = row["TABLE_NAME"].ToString();

                    }
                }

                if (n_rows > 0)
                {


                    s_excel_sql = String.Format(" SELECT TOP {0} * FROM [{1}] ", n_rows, System.IO.Path.GetFileNameWithoutExtension(s_table));
                }
                else
                {
                    s_excel_sql = String.Format(" SELECT * FROM [{0}] ", System.IO.Path.GetFileNameWithoutExtension(s_table));
                }

                command = new OleDbCommand(s_excel_sql, conn);
                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable exceldatatable = new DataTable();
                da.Fill(dt); //You will get the data in this dt datatable
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (command != null)
                {
                    command.Connection.Close();
                    command.Dispose();
                }
            }
            return RedirectToAction("Index");
        }

       
    }
}

So, you can copy the action from here and there we will use OLEDbCommand for creating a connection to the file, and then we will use OLEDbDataAdapter for reading the data from the Excel file which is provided in the connection.

You will see the data in the dt like this image


Issue The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

If you get any error saying The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine while using OLEDB then you will have to fix that error first and you can take reference from Solved 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. 

Just follow the steps from the article and you will be able to solve your error and then you will be able to use OLEDB.

So, this is how you can Import Excel in Asp.net MVC using OLE DB. There is one other way also to import Excel file in asp.net and that is by using ExcelDataReader which you can check below

Import Excel using Excel Data Reader

If you face an issue while working with OLE DB you can try working with Excel Data Reader. You can get all the steps of using ExcelDataReader from our article Import data from Excel in Asp.Net using ExcelDataReader. 

Let us know if you face any issues and comment if an issue doesn't solve for you. You can copy the code samples also.

S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Excel Export in Asp.Net MVC using XlWorkbook
Jun 11, 2022
Import data from Excel in Asp.Net
Sep 20, 2021
Integrate Stripe Payment Gateway In ASP.NET Core 8.0
Nov 23, 2023
How to Convert Text to Speech in Asp.Net
Nov 06, 2023

Comments

Tags

AspNet
C#
programming
AspNet MVC
c programming
AspNet Core
C
software development
tutorial
MVC
memory management
Paypal
coding
coding best practices
data structures
programming tutorial
tutorials
object oriented programming
Slick Slider
StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blogs
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
By Language
  • Angular
  • C
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page