OleDb를 사용하여 datagridview에서 SQL Server 데이터베이스에 Excel 시트를 삽입하려고합니다.SQL Server 데이터베이스에 Excel 시트 삽입
내가 사용하는 코드 :
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);
}
}
}
}
}
}
내 데이터베이스 이름은 다음과 같습니다 mohammed
및 테이블 이름은 두 개의 열 firstname
및 lastname
및 엑셀 시트 열 fname
및 lname
이다와 test
입니다 ..
문제는 내가 코드를 실행하고 button2에서 Excel 시트를 삽입 한 후 button1을 클릭하면 창 오류가 발생합니다.
,vshot32-clr2.exe은
어떤 도움 작동이 중지되었습니다하세요?
사용자가 원하는 것입니까 아니면 그냥 원하는 것입니까? 그것은 단지 당신을위한 경우 다음 관리 스튜디오를 사용하여 시트를 가져올 수 있습니다. 훨씬 쉽게. –