I am trying to insert an Excel sheet into a SQL Server database from datagridview using OleDb.
The code that I use :
namespace importfromexcel
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True");
// SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void button2_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;data source=" + ofd.FileName + @";Extended Properties=Excel 8.0;";
// Create Connection to Excel Workbook
//We can Import excel to sql server like this
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select fname,lname FROM [sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True";
// SqlCommand cmd;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "test";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
}
My database name is : mohammed
and the table name is test
with two columns firstname
and lastname
and the Excel sheet columns is fname
and lname
..
The problem is that when I execute the code and after insert the Excel sheet from button2 when I click button1 and I got an window error
vshot32-clr2.exe has stopped working
Any help please ??