我在将Excel的数据导入到SQL的时候老是出现下面的错误:
配置选项 'show advanced options' 已从 1 更改为 1。请运行 RECONFIGURE 语句进行安装。
配置选项 'Ad Hoc Distributed Queries' 已从 1 更改为 1。请运行 RECONFIGURE 语句进行安装。
消息 7399,级别 16,状态 1,第 1 行
链接服务器 "(null)" 的 OLE DB 访问接口 "MICROSOFT.JET.OLEDB.4.0" 报错。提供程序未给出有关错误的任何信息。
消息 7303,级别 16,状态 1,第 1 行
无法初始化链接服务器 "(null)" 的 OLE DB 访问接口 "MICROSOFT.JET.OLEDB.4.0" 的数据源对象。
我将代码贴出来,望大家帮忙指点一下啊!非常感谢!
///
/// 打开文件
///
///
///
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
ofd.Filter = "Excel 文件(*.xls)|";
ofd.ValidateNames = true;
ofd.CheckPathExists = true;
ofd.CheckFileExists = true;
string filepath = ofd.FileName;
this.textBox1.Text = filepath;
}
public void ExecMothod()
{
string sql = "EXEC sp_configure 'show advanced options', 1 /n GO /n RECONFIGURE /n GO /n "+
" EXEC sp_configure 'Ad Hoc Distributed Queries', 1 /n GO /n RECONFIGURE /n GO /n "+
" INSERT INTO tb_Lot SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,'Excel 5.0;HDR=YES;DATABASE=" + this.textBox1.Text.Trim() + "',sheet1$)";
string conStr = "server=.;database=MyTestDB;uid=sa;pwd=123456";
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int i= cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("数据导入成功");
}
else
{
MessageBox.Show("Error");
}
con.Close();
}
///
/// 导入
///
///
///
private void button1_Click(object sender, EventArgs e)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + this.textBox1.Text.Trim() + ";";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable dtSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataSet ds = new DataSet();
foreach (DataRow dr in dtSchema.Rows)
{
string table = dr["TABLE_NAME"].ToString();
string strExcel = "SELECT * FROM [" + table + "]";
ds.Tables.Add(table);
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, conn);
myCommand.Fill(ds, table);
}
ExecMothod();
conn.Close();
//KillProcess();
}