public DataSet ImportExcel(string file)
{
FileInfo fileInfo = new FileInfo(file);
if (!fileInfo.Exists) return null;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql = "select * from [Sheet1$]";
OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel); return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}
public bool ExportInfo(DataSet ds)
{
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)//如果ds中是有值的话 执行下面的操作
{
return Do(ds);//执行成功
}
}
return false;//执行失败
}
public bool Do(DataSet ds)
{
using (SqlConnection conn1 = new SqlConnection(DAO.connectionString))
{
if (conn1.State != ConnectionState.Open) conn1.Open();
SqlCommand commandNorthwind = conn1.CreateCommand();
commandNorthwind.CommandType = CommandType.Text;
SqlTransaction tranNorthwind = conn1.BeginTransaction();//开始事务
commandNorthwind.Transaction = tranNorthwind;
try
{
for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = ds.Tables[0].Rows[i];
string sql = "INSERT INTO G_GoodsType VALUES(" + int.Parse(dr[0].ToString())
+ ",'" + dr[1].ToString() + "','" + dr[2].ToString() + "','" + dr[3].ToString() + "') ";
commandNorthwind.CommandText = sql;
commandNorthwind.ExecuteNonQuery();//执行操作
}
commandNorthwind.Transaction.Commit();//提交事务
conn1.Close();//关闭数据库链接资源
return true;
}
catch//如果有异常 不一定要捕捉异常 但要rollback事务
{
if (commandNorthwind.Transaction != null && conn1 != null)
{
commandNorthwind.Transaction.Rollback();//rollback事务
conn1.Close();//关闭数据库链接
}
return false;
}
}
}
private void button1_Click(object sender, System.EventArgs e)
{
openFileDialog1.Filter = "电子表格(*.xls)|*.xls";
openFileDialog1.ShowDialog();//打开对话框
this.textBox1.Text = openFileDialog1.FileName;//得到文件=路径+名称
}
private void button2_Click(object sender, System.EventArgs e)
{
try
{
DataSet ds = ImportExcel(this.textBox1.Text);//将excel的对象先放到ds 中
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)//如果ds中是有值的话 执行下面的操作
{
if (ExportInfo(ds))
{
MessageBox.Show("导入数据库成功!");
}
else
{
MessageBox.Show("导入数据库失败!");
}
}
}
}
catch
{
MessageBox.Show("导入数据库失败 请检查导入文件是否填写正确!");
}
}