usando System.Data.SqlClient;
usando System.Data.OleDb;
private void tsmiImportTeacherInfo_Click(objeto remetente, EventArgs e)
{
Conjunto de dados ds;
if (ofdImport.ShowDialog()==DialogResult.OK)
{
ds = ImportExcel(this.ofdImport.FileName); //获得Excel
}
outro
{
retornar;
}
int odr = 0;
SqlConnection cn = db.sqlconnection();
tentar
{
cn.Open();
string str = "inserir nos valores do Professor (TeacherId,Pwd,eachCourse,TeacherName)(@TeacherId,@Pwd,@TeachCourse,@TeacherName)";
SqlCommand cmd = db.sqlcommand(str,cn);
int dsLength = ds.Tables[0].Rows.Count; //获得Excel中数据长度
for (int i = 0; i <dsLength; i++)
{
cmd.Parameters.Add("@TeacherId", SqlDbType.VarChar, 50).Value = ds.Tables["Teacher "].Rows[i][0];
cmd.Parameters.Add("@Pwd", SqlDbType.VarChar, 50).Value = ds.Tables["Professor "].Rows[i][1];
cmd.Parameters.Add("@TeachCourse", SqlDbType.VarChar, 300).Value = ds.Tables["Professor "].Rows[i][2];
cmd.Parameters.Add("@TeacherName", SqlDbType.VarChar, 50).Value = ds.Tables["Teacher "].Rows[i][3];
odr = cmd.ExecuteNonQuery();//提交
cmd.Parameters.Clear(); //清除前的赋值
}
//如果查到了数据,才使控制分页按钮生效
se (odr > 0)
{
MessageBox.Show("导入成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
cn.Fechar();
}
pegar (exceção ex)
{
jogue ex;
}
}
DataSet estático público ImportExcel (arquivo string)
{
FileInfo FileInfo = new FileInfo(arquivo);
se (!FileInfo.Exists)
{
retornar nulo;
}
string strcn = @"Provider=Microsoft.ACE.OLEDB.12.0;Fonte de dados=" + arquivo + ";Propriedades estendidas='Excel 12.0 Xml;HDR=YES;IMEX=1;'";
OleDbConnection cn = new OleDbConnection(strcn);
DataSet ds = new DataSet();
tentar
{
cn.Open();
string strcmd = "selecione * de [Planilha1$]";
OleDbDataAdapter da = new OleDbDataAdapter(strcmd,cn);
da.Fill(ds, "Professor");
retornar ds;
}
pegar (exceção ex)
{
jogue ex;
}
}
本文来自CSDN博客,转载请标明出处: http://blog.csdn.net/crx05/archive/2009/12/17/5023589.aspx
-