我正在尝试使用 OleDb 从 datagridview 将 Excel 工作表插入 SQL Server 数据库。
我使用的代码:
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
表名test
有两列firstname
,lastname
Excel工作表的列是fname
和lname
..
问题是,当我执行代码并在单击 button1 时从 button2 插入 Excel 工作表后出现窗口错误
vshot32-clr2.exe 已停止工作
请问有什么帮助吗??