Click here to Skip to main content
15,922,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi everyone,

I have been looking around recently for some codes that would allow me to upload an excel file and import the data into a database table but those that I have found dont seem to work.

Thanks,
Leroy
Posted
Comments
Sarath kumar.N 13-Aug-15 4:15am    
Which database u are using ?
Leroy Tan 13-Aug-15 4:19am    
Microsoft SQL Server Database File
Sarath kumar.N 13-Aug-15 4:22am    
Did u tried? If yes, what error u are getting?
Leroy Tan 13-Aug-15 4:31am    
I tried out this one http://www.aspsnippets.com/Articles/Read-and-Import-Excel-File-into-DataSet-or-DataTable-using-C-and-VBNet-in-ASPNet.aspx and the error I got was The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
Sarath kumar.N 13-Aug-15 4:33am    
No problem just install Database access engine.

1 solution

Try this below code on button import click

C#
protected void btnImport_Click(object sender, EventArgs e)
        {         
            if (!FileUpload1.HasFile)
            {
                try
                {
                    string path = string.Concat(Server.MapPath("~/Uploaded Folder/" + FileUpload1.FileName)); 
                    FileUpload1.SaveAs(path);
 
                    // Connection String to Excel Workbook
                    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
                    OleDbConnection connection = new OleDbConnection();
                    connection.ConnectionString = excelConnectionString;
                    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
                    connection.Open();
                    // Create DbDataReader to Data Worksheet
                    DbDataReader dr = command.ExecuteReader();
 
                    // SQL Server Connection String
                    string sqlConnectionString = @"Data Source=MYPC;Initial Catalog=Student;User ID=sa;Password=wintellect";
 
                   // Bulk Copy to SQL Server 
                    SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
                    bulkInsert.DestinationTableName = "Student_Record";
                    bulkInsert.WriteToServer(dr);
                    Label1.Text = "Ho Gaya";
                }

Catch(Exception ex)
{
         label.text=ex.Message.ToString();
}
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900