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, 1:42 AM EST
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, 7:58 AM EDT
The path is not of a legal form error
Yayat YatimanPosted Oct 12, 2023, 1:52 AM EDT
Hi Mr Vithal, i have error message "could not find installable isam." please help
Shyamsundar baralPosted Jan 25, 2023, 7:22 AM EST
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, 12:29 PM EDT
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 28, 2018, 10:48 PM EST
'No Value given for one or more parameters' please help
Raj KumarPosted Jun 17, 2018, 1:00 AM EDT
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 27, 2018, 8:30 PM EDT
This code is very helpful and my requirement is sql table should not take duplicate id while importing csv to sql
Geet PriyadarshiniPosted Mar 14, 2018, 8:00 PM EDT
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, 3:16 AM EST
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, 6:54 PM EST
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 14, 2018, 10:50 PM EST
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, 6:57 AM EST
Use string CurrentFilePath = Path.GetFileName(FileUpload1.PostedFile.FileName); string excelPath = Server.MapPath("~/Files/") + CurrentFilePath; FileUpload1.SaveAs(excelPath); InsertExcelRecords(excelPath);
BIJO RAJANPosted Jan 12, 2018, 6:57 AM EST
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, 6:56 AM EST
Here is the fix which i found.
BIJO RAJANPosted Jan 10, 2018, 12:13 AM EST
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, 5:06 AM EST
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 6, 2017, 10:13 PM EDT
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, 1:09 AM EDT
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, 4:06 PM EDT
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 28, 2017, 10:04 PM EDT
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, 11:38 AM EDT
This does not work
veera muthuPosted Feb 14, 2017, 12:21 AM EST
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, 1:41 AM EST
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, 1:39 AM EST
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, 1:37 AM EST
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 3, 2017, 9:24 PM EST
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, 3:58 PM EDT
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, 3:55 PM EDT
Yes, I am using the same code.
Vithal WadjeTOP 100Posted Sep 9, 2016, 4:22 AM EDT
Yes offcource you need to use it , are you using same code which is preceding article ?
Tony WoodsPosted Sep 8, 2016, 4:00 PM EDT
DO i need to use ""using System.Web.UI.WebControls;""?
Tony WoodsPosted Sep 8, 2016, 3:59 PM EDT
I have checked the FileUploader id in both aspx and cs files both are same
Vithal WadjeTOP 100Posted Sep 7, 2016, 12:58 AM EDT
Check your FileUploader id
Tony WoodsPosted Sep 6, 2016, 12:05 PM EDT
"""CS0103 The name 'FileUpload1' does not exist in the current context""", please let me know why am i getting this error
Vithal WadjeTOP 100Posted Aug 20, 2016, 6:38 PM EDT
Welcome
Aniket NarvankarPosted Aug 17, 2016, 10:09 PM EDT
Ok Thanks Sir I got the Solution
Vithal WadjeTOP 100Posted Aug 16, 2016, 9:09 AM EDT
Yes you need to change as per excel file extension .
Aniket NarvankarPosted Aug 16, 2016, 5:43 AM EDT
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 WadjeTOP 100Posted Aug 12, 2016, 6:31 AM EDT
Its Excel sheet name , one excel file contains multiple sheets .
Aniket NarvankarPosted Aug 12, 2016, 2:43 AM EDT
What is Sheet1$ used for did not understood,please do let me know about it
Vithal WadjeTOP 100Posted Jul 4, 2016, 7:14 PM EDT
Hi varsha desai install Microsoft.ACE.OLEDB.12.0 on your machine , its missing
varsha desaiPosted Jul 4, 2016, 3:40 AM EDT
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, 3:40 AM EDT
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 WadjeTOP 100Posted Jun 21, 2016, 9:20 PM EDT
welcome
Phani KosuriPosted Jun 21, 2016, 2:09 PM EDT
thank you its help me. keep going
Vithal WadjeTOP 100Posted May 30, 2016, 6:39 AM EDT
Check your file opened in background using task manager and close the all that file related process
Hakim ChandioPosted May 24, 2016, 10:26 PM EDT
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 5, 2016, 10:38 PM EDT
why oledb connection in sql?
Vithal WadjeTOP 100Posted Apr 14, 2016, 8:47 AM EDT
Riddhi Valecha , Can u explain in detail what you wants
Riddhi ValechaPosted Apr 14, 2016, 3:34 AM EDT
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, 6:06 PM EDT
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, 6:55 PM EST
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 13, 2015, 8:37 PM EST
what is FileUpload1 in context
mohamed elhosenyPosted Dec 12, 2015, 6:13 AM EST
realy tank you for wonderful effort.
Vithal WadjeTOP 100Posted Nov 15, 2015, 7:50 PM EST
Thanks
Jerald FergusonPosted Nov 15, 2015, 4:59 PM EST
Great info. How can I get this to work for a table where 'id' is an auto-incremented field?
Talha MalikPosted Nov 2, 2015, 9:53 PM EST
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 WadjeTOP 100Posted Aug 26, 2015, 10:51 AM EDT
check whether the selected excel file for upload is opened in somewhere ,check using task manager and close it
abhishek pachchigarPosted Aug 26, 2015, 10:24 AM EDT
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, 10:23 AM EDT
Hello sir I get this error
Vithal WadjeTOP 100Posted Aug 26, 2015, 7:41 AM EDT
veera muthu refer my other articles for same
Vithal WadjeTOP 100Posted Aug 26, 2015, 7:40 AM EDT
Priya madam wait my next article
veera muthuPosted Aug 25, 2015, 10:53 PM EDT
thanku....But i need sql data to excel sheet..give me a solution
aman rastogiPosted Aug 25, 2015, 10:09 PM EDT
Can you tell me, how to achieve the same, if I am not using FileUploadControl. I am using simple HTML + AngularJS + webAPi
PriyaPosted Aug 10, 2015, 10:35 PM EDT
Am facing this error: The name 'path' doesnt exist in the current context
Vithal WadjeTOP 100Posted Aug 8, 2015, 3:09 AM EDT
check your fileuploader control Id
jagadeesh PoosalaPosted Aug 5, 2015, 11:07 PM EDT
Please help me on this... Thanks in Advance.
jagadeesh PoosalaPosted Aug 5, 2015, 11:07 PM EDT
Am facing this error: The name 'FileUpload1' doesnt exist in the current context
Vithal WadjeTOP 100Posted Jun 4, 2015, 9:24 AM EDT
thanks Upendra
Vithal WadjeTOP 100Posted Jun 4, 2015, 8:39 AM EDT
Sheet1 is your excel file sheet name
Harsha ChunduriPosted Jun 4, 2015, 12:38 AM EDT
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 3, 2015, 11:13 PM EDT
nice
Vithal WadjeTOP 100Posted Apr 7, 2015, 9:07 AM EDT
thanks
Gowtham RajamanickamTOP 100Posted Apr 6, 2015, 9:51 AM EDT
simply superb
Vithal WadjeTOP 100Posted Mar 11, 2015, 7:46 AM EDT
its an excel sheet number
Chandra SekharPosted Mar 11, 2015, 6:41 AM EDT
what is the 'sheet1$' in the above query
Chandra SekharPosted Mar 11, 2015, 6:41 AM EDT
Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
Aman SinghPosted Feb 13, 2015, 7:21 AM EST
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 14, 2015, 9:53 PM EST
Ok tahnks!
Vithal WadjeTOP 100Posted Dec 22, 2014, 5:15 AM EST
OK thanks
Guest UserPosted Dec 22, 2014, 4:21 AM EST
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, 4:20 AM EST
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, 4:19 AM EST
Your article represents OLEDB mechanism to read via Excel records.
Vithal WadjeTOP 100Posted Dec 21, 2014, 5:12 PM EST
Thanks Michal Habalcik sir
Vithal WadjeTOP 100Posted Dec 21, 2014, 5:11 PM EST
thanks Jitendra Kumar sir
Michal HabalcikPosted Dec 21, 2014, 11:37 AM EST
Great tutorial
Jitendra KumarPosted Dec 21, 2014, 7:22 AM EST
Nice one..