Background
I have often read the common question in forum posts, how to upload Excel file records into a database but no one has provided the proper solution and many solutions contain a lot of code that is not required so by considering the preceding requirements I have decided to write this article to provide the solution to insert Excel file records into the database with a minimum amount of code. So let us start creating an application so beginners can also understand.
First create the table named Employee using the following script:
- CREATE TABLE [dbo].[Employee](
- [id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [Address] [varchar](50) NULL,
- [Designation] [varchar](50) NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
Create the same Excel file with the following records:
Now Let us create the sample web application as follows:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the web site a name such as "InsertExcelFileIntoDataBase" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
- Drag and drop one Button and FileUploader controler onto the <form> section of the Default.aspx page.
Now the default.aspx Page source code will look such as follows.
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Article by Vithal Wadje</title>
- </head>
- <body bgcolor="blue">
- <form id="form1" runat="server">
- <div style="color: White;">
- <h4>
- Article for C#Corner
- </h4>
- <table>
- <tr>
- <td>
- Select File
- </td>
- <td>
- <asp:FileUpload ID="FileUpload1" runat="server" />
- </td>
- <td>
- </td>
- <td>
- <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
Now open the Default.aspx.cs page and write the following code to create an oledbconnection for the Excel file as in the following:
- private void ExcelConn(string FilePath)
- {
- constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
- Econ = new OleDbConnection(constr);
- }
Create a function for Sqlconnection as:
- private void connection()
- {
- sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
- con = new SqlConnection(sqlconn);
- }
Create a function to read and insert an Excel File into the database as:
- private void InsertExcelRecords(string FilePath)
- {
- ExcelConn(FilePath);
- Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
- OleDbCommand Ecom = new OleDbCommand(Query, Econ);
- Econ.Open();
- DataSet ds=new DataSet();
- OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
- Econ.Close();
- oda.Fill(ds);
- DataTable Exceldt = ds.Tables[0];
- connection();
- //creating object of SqlBulkCopy
- SqlBulkCopy objbulk = new SqlBulkCopy(con);
- //assigning Destination table name
- objbulk.DestinationTableName = "Employee";
- //Mapping Table column
- objbulk.ColumnMappings.Add("Name", "Name");
- objbulk.ColumnMappings.Add("City", "City");
- objbulk.ColumnMappings.Add("Address", "Address");
- objbulk.ColumnMappings.Add("Designation", "Designation");
- //inserting Datatable Records to DataBase
- con.Open();
- objbulk.WriteToServer(Exceldt);
- con.Close();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
- InsertExcelRecords(CurrentFilePath);
- }
The entire code of the default.aspx.cs page will look as follows:
- using System;
- using System.Data;
- using System.IO;
- using System.Data.OleDb;
- using System.Configuration;
- using System.Data.SqlClient;
- public partial class _Default : System.Web.UI.Page
- {
- OleDbConnection Econ;
- SqlConnection con;
- string constr,Query,sqlconn;
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- private void ExcelConn(string FilePath)
- {
- constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
- Econ = new OleDbConnection(constr);
- }
- private void connection()
- {
- sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
- con = new SqlConnection(sqlconn);
- }
- private void InsertExcelRecords(string FilePath)
- {
- ExcelConn(FilePath);
- Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
- OleDbCommand Ecom = new OleDbCommand(Query, Econ);
- Econ.Open();
- DataSet ds=new DataSet();
- OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
- Econ.Close();
- oda.Fill(ds);
- DataTable Exceldt = ds.Tables[0];
- connection();
- //creating object of SqlBulkCopy
- SqlBulkCopy objbulk = new SqlBulkCopy(con);
- //assigning Destination table name
- objbulk.DestinationTableName = "Employee";
- //Mapping Table column
- objbulk.ColumnMappings.Add("Name", "Name");
- objbulk.ColumnMappings.Add("City", "City");
- objbulk.ColumnMappings.Add("Address", "Address");
- objbulk.ColumnMappings.Add("Designation", "Designation");
- //inserting Datatable Records to DataBase
- con.Open();
- objbulk.WriteToServer(Exceldt);
- con.Close();
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
- InsertExcelRecords(CurrentFilePath);
- }
- }
Now click on the Upload button and see the records in the database table as:
Now you have seen how the records are inserted into the database with minimal code and effort.
Notes
- For detailed code please download the sample Zip file.
- Do a proper validation such as date input values when implementing.
- Make the changes in the web.config file depending on your server details for the connection string.
Summary
From all the preceding examples you have learned how to insert Excel records into the database. I hope this article is useful for all readers, if you have a suggestion then please contact me.

purvesh pachchigarPosted Feb 21, 2024, 6:42 AM
The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.
sagar shindePosted Oct 17, 2023, 11:58 AM
The path is not of a legal form error
Yayat YatimanPosted Oct 12, 2023, 5:52 AM
Hi Mr Vithal, i have error message "could not find installable isam." please help
Shyamsundar baralPosted Jan 25, 2023, 12:22 PM
The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.' what was the solution
Tejas PatelPosted Aug 19, 2022, 4:29 PM
The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
zenani mthembuPosted Nov 29, 2018, 3:48 AM
'No Value given for one or more parameters' please help
Raj KumarPosted Jun 17, 2018, 5:00 AM
The Microsoft Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
Uday KrishnaPosted Apr 28, 2018, 12:30 AM
This code is very helpful and my requirement is sql table should not take duplicate id while importing csv to sql
Geet PriyadarshiniPosted Mar 15, 2018, 12:00 AM
I wrote the code exactly what you write but my excel file is not imported in the database. Can you tell me why this is happening ?
dabbu kumarPosted Mar 5, 2018, 8:16 AM
How to fix: The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
Rajneesh ChaubeyPosted Jan 29, 2018, 11:54 PM
Amazing article Vithal. I have one question, can we upload data to multiple tables using single excel file. Like in above case you are inserting to single table. I want something like id, name and address goes to one table whereas designation and id goes to another table. Can we do that??
Rajesh GaddamPosted Jan 15, 2018, 3:50 AM
Getting the error like Invalid operation exception at Econ.Open and The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
BIJO RAJANPosted Jan 12, 2018, 11:57 AM
Use string CurrentFilePath = Path.GetFileName(FileUpload1.PostedFile.FileName); string excelPath = Server.MapPath("~/Files/") + CurrentFilePath; FileUpload1.SaveAs(excelPath); InsertExcelRecords(excelPath);
BIJO RAJANPosted Jan 12, 2018, 11:57 AM
Ignore protected void Button1_Click(object sender, EventArgs e) { string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName); InsertExcelRecords(CurrentFilePath); } and use
BIJO RAJANPosted Jan 12, 2018, 11:56 AM
Here is the fix which i found.
BIJO RAJANPosted Jan 10, 2018, 5:13 AM
Pleae..i get this error..The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.
nirmit shahPosted Dec 5, 2017, 10:06 AM
How to check each excel field record before insert to prevent wrong entry in database for example in database id=456 in excel 1456 so i want to check id before insert record in data base using sqlbulk copy excel import
anil babuPosted Aug 7, 2017, 2:13 AM
I am geeting this error like this "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine".
Raji BaskarPosted Jun 16, 2017, 5:09 AM
Hi... I get this error "System.NullReferenceException: Object reference not set to an instance of an object." in this line "sqlconn = ConfigurationManager.ConnectionStrings["con"].ConnectionString; " kindly help.........
Christian OforiPosted May 31, 2017, 8:06 PM
Please im getting this error.The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path correctly.
yogesh jadonPosted May 29, 2017, 2:04 AM
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data.
freel yodaPosted Apr 24, 2017, 3:38 PM
This does not work
veera muthuPosted Feb 14, 2017, 5:21 AM
Its very good. I don't have column name like id,name. I need read data from excel to sql table without Header or based on column count. please help me.
ankit dixitPosted Feb 4, 2017, 6:41 AM
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
ankit dixitPosted Feb 4, 2017, 6:39 AM
The Microsoft Office Access database engine could not find the object 'Sheet$'. Make sure the object exists and that you spell its name and the path name correctly.
ankit dixitPosted Feb 4, 2017, 6:37 AM
The Microsoft Office Access database engine could not find the object 'Employee'. Make sure the object exists and that you spell its name and the path name correctly.
Shruthi HDPosted Feb 4, 2017, 2:24 AM
String CurrentFilePath = Path.GetFullPath(ExcelUpload.PostedFile.FileName) <-- in this line m getting thhis error -->Object reference not set to an instance of an object.
Tony WoodsPosted Sep 9, 2016, 7:58 PM
If i am using the that "using statement" mentioned above, an error saying ""file upload is a type, which is not valid in the given context""
Tony WoodsPosted Sep 9, 2016, 7:55 PM
Yes, I am using the same code.
Vithal WadjePosted Sep 9, 2016, 8:22 AM
Yes offcource you need to use it , are you using same code which is preceding article ?
Tony WoodsPosted Sep 8, 2016, 8:00 PM
DO i need to use ""using System.Web.UI.WebControls;""?
Tony WoodsPosted Sep 8, 2016, 7:59 PM
I have checked the FileUploader id in both aspx and cs files both are same
Vithal WadjePosted Sep 7, 2016, 4:58 AM
Check your FileUploader id
Tony WoodsPosted Sep 6, 2016, 4:05 PM
"""CS0103 The name 'FileUpload1' does not exist in the current context""", please let me know why am i getting this error
Vithal WadjePosted Aug 20, 2016, 10:38 PM
Welcome
Aniket NarvankarPosted Aug 18, 2016, 2:09 AM
Ok Thanks Sir I got the Solution
Vithal WadjePosted Aug 16, 2016, 1:09 PM
Yes you need to change as per excel file extension .
Aniket NarvankarPosted Aug 16, 2016, 9:43 AM
Ok,Sir this I understood,now If I want to upload xls file then will this work or do I need to change the provider From Microsoft.ACE.OLEDB.12.0 to Microsoft.JET.OLEDB.8.0,please do let me know about it,I am confused upon this
Vithal WadjePosted Aug 12, 2016, 10:31 AM
Its Excel sheet name , one excel file contains multiple sheets .
Aniket NarvankarPosted Aug 12, 2016, 6:43 AM
What is Sheet1$ used for did not understood,please do let me know about it
Vithal WadjePosted Jul 4, 2016, 11:14 PM
Hi varsha desai install Microsoft.ACE.OLEDB.12.0 on your machine , its missing
varsha desaiPosted Jul 4, 2016, 7:40 AM
Hi, Iam Getting an Error (The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine), How to fix this, Please help me
varsha desaiPosted Jul 4, 2016, 7:40 AM
Hi, Iam Getting an Error (The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine), How to fix this, Please help me
Vithal WadjePosted Jun 22, 2016, 1:20 AM
welcome
Phani KosuriPosted Jun 21, 2016, 6:09 PM
thank you its help me. keep going
Vithal WadjePosted May 30, 2016, 10:39 AM
Check your file opened in background using task manager and close the all that file related process
Hakim ChandioPosted May 25, 2016, 2:26 AM
My error is : The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data. . can you please help me
Sathish KumarPosted May 6, 2016, 2:38 AM
why oledb connection in sql?
Vithal WadjePosted Apr 14, 2016, 12:47 PM
Riddhi Valecha , Can u explain in detail what you wants
Riddhi ValechaPosted Apr 14, 2016, 7:34 AM
Hi...I also would like to know - If the name of person is unique, then in this case how do I fire an update query ?
Ramesh KaamarthiPosted Mar 30, 2016, 10:06 PM
Hi, Iam Getting an Error (The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine), How to fix this, Please help me
asif redoyPosted Jan 6, 2016, 11:55 PM
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly" I am also getting the same error how to fix it ???????? plz urgent help needed
Farrukh LiaqatPosted Dec 14, 2015, 1:37 AM
what is FileUpload1 in context
mohamed elhosenyPosted Dec 12, 2015, 11:13 AM
realy tank you for wonderful effort.
Vithal WadjePosted Nov 16, 2015, 12:50 AM
Thanks
Jerald FergusonPosted Nov 15, 2015, 9:59 PM
Great info. How can I get this to work for a table where 'id' is an auto-incremented field?
Talha MalikPosted Nov 3, 2015, 2:53 AM
What is "Sheet1$" I am getting an error that : "The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly"
Vithal WadjePosted Aug 26, 2015, 2:51 PM
check whether the selected excel file for upload is opened in somewhere ,check using task manager and close it
abhishek pachchigarPosted Aug 26, 2015, 2:24 PM
The Microsoft Office Access database engine cannot open or write to the file ''. It is already opened exclusively by another user, or you need permission to view and write its data. pls help me
abhishek pachchigarPosted Aug 26, 2015, 2:23 PM
Hello sir I get this error
Vithal WadjePosted Aug 26, 2015, 11:41 AM
veera muthu refer my other articles for same
Vithal WadjePosted Aug 26, 2015, 11:40 AM
Priya madam wait my next article
veera muthuPosted Aug 26, 2015, 2:53 AM
thanku....But i need sql data to excel sheet..give me a solution
aman rastogiPosted Aug 26, 2015, 2:09 AM
Can you tell me, how to achieve the same, if I am not using FileUploadControl. I am using simple HTML + AngularJS + webAPi
PriyaPosted Aug 11, 2015, 2:35 AM
Am facing this error: The name 'path' doesnt exist in the current context
Vithal WadjePosted Aug 8, 2015, 7:09 AM
check your fileuploader control Id
jagadeesh PoosalaPosted Aug 6, 2015, 3:07 AM
Please help me on this... Thanks in Advance.
jagadeesh PoosalaPosted Aug 6, 2015, 3:07 AM
Am facing this error: The name 'FileUpload1' doesnt exist in the current context
Vithal WadjePosted Jun 4, 2015, 1:24 PM
thanks Upendra
Vithal WadjePosted Jun 4, 2015, 12:39 PM
Sheet1 is your excel file sheet name
Harsha ChunduriPosted Jun 4, 2015, 4:38 AM
Hello Sir, I am getting following error while executing : The Microsoft Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet1$' is not a local object, check your network connection or contact the server administrator.
Upendra Pratap ShahiPosted Jun 4, 2015, 3:13 AM
nice
Vithal WadjePosted Apr 7, 2015, 1:07 PM
thanks
Gowtham RajamanickamPosted Apr 6, 2015, 1:51 PM
simply superb
Vithal WadjePosted Mar 11, 2015, 11:46 AM
its an excel sheet number
Chandra SekharPosted Mar 11, 2015, 10:41 AM
what is the 'sheet1$' in the above query
Chandra SekharPosted Mar 11, 2015, 10:41 AM
Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
Aman SinghPosted Feb 13, 2015, 12:21 PM
Vithal Wadje; Hello sir i have gone thru this and able to insert in database bt my requirement is i have to fetch data from excel and den encrypt the data of one particular column as example consider here it is designation column and den save in database, i have readymade encryption algo for this. How should dis will be done, plz help regarding this.
Dharmveer SinghPosted Jan 15, 2015, 2:53 AM
Ok tahnks!
Vithal WadjePosted Dec 22, 2014, 10:15 AM
OK thanks
Guest UserPosted Dec 22, 2014, 9:21 AM
The other popular mechanism these days is OpenXML which deals with generally .xlsx format. There are numerous nuget packages available for the same, my personal favorite is ClosedXML. I just wanted to share this information via your good article. Thanks Vithal Wadje for penning this down!
Guest UserPosted Dec 22, 2014, 9:20 AM
Good example mentioned. There are two other ways of eXcel handling. The old way is adding Excel dll i.e., Interop services. This is not suggested approach, as its heavy operation
Guest UserPosted Dec 22, 2014, 9:19 AM
Your article represents OLEDB mechanism to read via Excel records.
Vithal WadjePosted Dec 21, 2014, 10:12 PM
Thanks Michal Habalcik sir
Vithal WadjePosted Dec 21, 2014, 10:11 PM
thanks Jitendra Kumar sir
Michal HabalcikPosted Dec 21, 2014, 4:37 PM
Great tutorial
Jitendra KumarPosted Dec 21, 2014, 12:22 PM
Nice one..