Import Data From Excel to Access with ASP.NET

Building on my previous article on importing text files of various formats to an Access database, here's how to do the same thing simply and efficiently with Excel files.

For this particular example, I have an Excel Workbook with one Worksheet, which is named by default, Sheet1. In it, I have a header row, with FirstName, SecondName and Age as the column headings. Thereafter is a selection of data:

Excel Sheet1

I also have an Access database called contacts.mdb, with a table called Persons. The schema of the table matches the Excel sheet, with the addition of an Autonumber column:

Excel2

Both of these files are in the App_Data folder of a web site, so the only thing to do is to read the data out of Excel and into Access. As I mentioned in my previous article, the Jet 4.0 driver can connect to a variety of file types, including Access and Excel. The only difference each time is in the connection string. For Excel, a typical connection string will look like this:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0";

Making sure I have referenced System.Data.OleDb, here is the code that transfers the records across from Excel to Access:

[C#]
string Access = Server.MapPath("App_Data/contacts.mdb");
string Excel = Server.MapPath("App_Data/Book1.xls");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel +";Extended Properties=Excel 8.0;";
using (OleDbConnection conn = new OleDbConnection(connect))
{
  using (OleDbCommand cmd = new OleDbCommand())
  {
    cmd.Connection = conn;
    cmd.CommandText = "INSERT INTO [MS Access;Database=" + Access + "].[Persons] SELECT * FROM [Sheet1$]";
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}
[VB]
Dim Access As String = Server.MapPath("App_Data/contacts.mdb")
Dim Excel As String = Server.MapPath("App_Data/Book1.xls")
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Excel & _
    ";Extended Properties=Excel 8.0;"
Using conn As New OleDbConnection(connect)
  Using cmd As New OleDbCommand()
    cmd.Connection = conn
    cmd.CommandText = "INSERT INTO [MS Access;Database=" & Access & "].[Persons] SELECT * FROM [Sheet1$]"
    conn.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

Notice that the INSERT INTO statement points to the Access database by stating the type of application that is to be used (MS Access;), and the full path to the actual mdb file. Following that is the dot separator and the name of the target table. As with all references to worksheets in Excel, the name of the sheet in the FROM clause has a $ sign appended to it. The above statement will result in the records from Excel being appended to the relevant table in Access.

Creating a new Table

A slight alteration to the SQL will result in a new table being created in the Access database, into which the records will be copied, along with the header row as field names:

[C#]
string Access = Server.MapPath("App_Data/contacts.mdb");
string Excel = Server.MapPath("App_Data/Book1.xls");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel +";Extended Properties=Excel 8.0;";
using (OleDbConnection conn = new OleDbConnection(connect))
{
  using (OleDbCommand cmd = new OleDbCommand())
  {
    cmd.Connection = conn;
    cmd.CommandText = "SELECT * INTO [MS Access;Database=" + Access + "].[New Table] FROM [Sheet1$]";
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}
[VB]
Dim Access As String = Server.MapPath("App_Data/contacts.mdb")
Dim Excel As String = Server.MapPath("App_Data/Book1.xls")
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Excel & _
    ";Extended Properties=Excel 8.0;"
Using conn As New OleDbConnection(connect)
  Using cmd As New OleDbCommand()
    cmd.Connection = conn
    cmd.CommandText = "SELECT * INTO [MS Access;Database=" & Access & "].[New Table] FROM [Sheet1$]"
    conn.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

And the result:

 

Date Posted:
Last Updated:
Posted by:
Total Views to date: 71838

14 Comments

- priya

hai
i has gone through this website..i am trying to read the data from excel and display in the gridview.
while running the folling code

protected void Page_Load(object sender, EventArgs e)
{

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("s.xls") + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connectionString);
objConn.Open();
String strConString = "SELECT firstColumnName FROM [Sheet1$]";
//where date = CDate('" + DateTime.Today.ToShortDateString() + "')";
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataReader r = objCmdSelect.ExecuteReader();
GridView1.DataSource = r;
GridView1.DataBind();
objConn.Close();
}


i got this error at runtime:

The Microsoft Jet database engine could not find the object 'Sheet1'. Make sure the object exists and that you spell its name and the path name correctly.


- Mike

@priya

I suggest you ask you question in a general ASP.NET forum, like the one at http://forums.asp.net. But first, make sure that the sheet exists and that you have spelt its name and the name of the path to the file correctly.

- m

Genious! thanks!

- durgesh pratap singh

hi priya

u can use this code for import data from excel sheet to
griedview directly.

string Access = Server.MapPath("App_Data/contacts.mdb");
string Excel = Server.MapPath("App_Data/Book1.xls");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
conn.Close();

}
}

- serefkoca

thanks this article.
---------------------------------------
string Access = Server.MapPath("App_Data/contacts.mdb");
string Excel = Server.MapPath("App_Data/Book1.xls");
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
conn.Close();
------------------------------------------
I want export data gridwiev to access.

if you write export to access code . I will to be very happy

- usha

Dear Mike,
Can you pl. provide ASP code,
how to upload excel file to server pc. My ASP code is working well when i test in my localhost. But when the Accessdb is in server, the excel file selected by any user as per the access table shd. able to download data to access and display data in the table on asp page. Kindly provide me the necessary code. tq.

- Paul Watson

Hi Mike,

i am trying to append excel data into an access table just like you have done above, my cmd object reads exactly the same as yours, except that i ahve changed the excel sheet and access table names to suit my needs, however, instead of the data appending to the Table, a OledbException is firing stating that The table i am trying to append to already exists.

i'm a little confused.

Thank you

Paul

- Paul Watson

I have it working now, sorry to be a nuisance.

- Madhukar

Excellent

- Fern

Thanks so much for suggestion.

- Natalie

What about impor text file with delimeter ',' into Access?

- Mike

@Natalie,

This article covers that for you: Reading Text files into Access with ASP.NET

- sivakumar

very nice
thanking you

- pinal

thank you
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Anh Huynh 4/27/2015 3:51 PM
In response to Create PDFs in ASP.NET - getting started with iTextSharp
I can't get a WRITE access to the online server so I change the method from FileStream to and it for...

Rogerio 4/24/2015 11:16 PM
In response to Adding Search
Hi, great post. Congratulations. @mb, you could make your parameters optional and just at of your...

chandradev 4/24/2015 11:53 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
very nice article. Thanks for sharing with us....

Lokesh 4/24/2015 9:06 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Excellent Article..!! Thanks Mike :)...

kawish 4/24/2015 7:04 AM
In response to Using The Themes Helper In Razor Web Pages
Nice:)...

Mahdi 4/23/2015 9:49 PM
In response to Adding a New Row In The Razor WebGrid
Thank u very very. its useful for me...

Jerrie Pelser 4/23/2015 4:24 PM
In response to Entity Framework 6 Recipe: Storing And Managing Time
Nice article Mike! I think there is an error in the House property getter of MovieFormModel. Your...

mike 4/22/2015 4:45 PM
In response to Parameter Queries in ASP.NET with MS Access
If the insert statement got failed how w can i get the error message of as string?...

frank 4/22/2015 9:44 AM
In response to Sessions in ASP.NET 5
Mike can you write up an article showcasing the difference / upgrade paths of ASP.net Web Pages and...

Scott 4/21/2015 11:39 PM
In response to ASP.NET MVC DropDownLists - Multiple Selection and Enum Support
Excellent! Just what I need for the current application I am working on. Even to the extent that I a...