menggunakan Sistem.Data.SqlClient;
menggunakan Sistem.Data.OleDb;
private void tsmiImportTeacherInfo_Click(pengirim objek, EventArgs e)
{
Kumpulan Data ds;
jika (ofdImport.ShowDialog()==DialogResult.OK)
{
ds = ImportExcel(ini.ofdImport.NamaFile); //获得Excel
}
kalau tidak
{
kembali;
}
int aneh = 0;
SqlConnection cn = db.sqlconnection();
mencoba
{
cn.Buka();
string str = "masukkan ke nilai Guru (TeacherId,Pwd,eachCourse,TeacherName)(@TeacherId,@Pwd,@TeachCourse,@TeacherName)";
SqlCommand cmd = db.sqlcommand(str,cn);
int dsLength = ds.Tabel[0].Baris.Hitungan; //获得Excel中数据长度
untuk (int i = 0; i < dsPanjang; 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["Teacher "].Rows[i][1];
cmd.Parameters.Add("@TeachCourse", SqlDbType.VarChar, 300).Value = ds.Tables["Teacher "].Rows[i][2];
cmd.Parameters.Add("@TeacherName", SqlDbType.VarChar, 50).Value = ds.Tables["Teacher "].Rows[i][3];
odr = cmd.ExecuteNonQuery();//提交
cmd.Parameter.Hapus(); //清除前的赋值
}
//如果查到了数据,才使控制分页按钮生效
jika (ganjil > 0)
{
MessageBox.Show("导入成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
cn.Tutup();
}
menangkap (Pengecualian ex)
{
membuang mantan;
}
}
DataSet statis publik ImportExcel (file string)
{
FileInfo FileInfo = FileInfo baru(file);
if (!FileInfo.Ada)
{
kembalikan nol;
}
string strcn = @"Provider=Microsoft.ACE.OLEDB.12.0;Sumber Data=" + file + ";Properti Diperluas='Excel 12.0 Xml;HDR=YA;IMEX=1;'";
OleDbConnection cn = OleDbConnection baru(strcn);
Kumpulan Data ds = Kumpulan Data baru();
mencoba
{
cn.Buka();
string strcmd = "pilih * dari [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(strcmd,cn);
da.Isi(ds, "Guru");
kembali ds;
}
menangkap (Pengecualian ex)
{
membuang mantan;
}
}
Lihat tautan CSDN ke: http://blog.csdn.net/crx05/archive/2009/12/17/5023589.aspx
-