从Excel到datagridview到SQL
我现在已经把EXcel表里的数据绑定显示到datagridview中,现在想把这些数据存到SQL数据库中,为什么数据库里老是没有更新呢。
这是从EXcel到datagridview
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
ofd.Title = "打开Excel";
ofd.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx";
//ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
ofd.ValidateNames = true; //验证用户是否输入一个有效的windows文件名
ofd.CheckPathExists = true; //检查路径是否存在
ofd.CheckFileExists = true; //检查文件是否存在
ofd.RestoreDirectory = true; //控制对话框在关闭之前是否恢复当前目录
string str = @""+ofd.FileName; //定义所要连接excel表的位置为打开文件的位置
if ( !string.IsNullOrEmpty(str))
{
try
{
string strOdbcCon ="Provider=Microsoft.ACE.OleDb.12.0;" + "Data Source="+str+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";//设置Excel文件位置
OleDbConnection OleDB = new OleDbConnection(strOdbcCon);
OleDbDataAdapter OleDat = new OleDbDataAdapter("select*from[sheet1$]", OleDB);
DataTable dt = new DataTable();
OleDat.Fill(dt);
this.dgv_motor.DataSource = dt.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //弹出异常提示信息
}
}
else
{
MessageBox.Show("您要导入的文件错误!");
}
这是从datagridview到SQL数据库
SqlConnection con = new SqlConnection("Data source=.;Initial Catalog=driveselect;" + "Integrated Security=True");//连接数据库
con.Open();
String tempStrSQL;
for (int i = 0; i < this.dgv_motor.Rows.Count; i++)
{
if (this.dgv_motor.Rows[i].Cells[0].Value == null&&bool.Parse(dgv_motor.Rows[i].Cells[0].Value.ToString()) == false)
{
break;
}
else
{
String device_code = dgv_motor.Rows[i].Cells[0].Value.ToString().Trim();
String name = dgv_motor.Rows[i].Cells[1].Value.ToString().Trim();
String number = dgv_motor.Rows[i].Cells[2].Value.ToString().Trim();
String power = dgv_motor.Rows[i].Cells[3].Value.ToString().Trim();
String voltage = dgv_motor.Rows[i].Cells[4].Value.ToString().Trim();
String M_current = dgv_motor.Rows[i].Cells[5].Value.ToString().Trim();
String M_override = dgv_motor.Rows[i].Cells[6].Value.ToString().Trim();
String total_power = dgv_motor.Rows[i].Cells[7].Value.ToString().Trim();
String sendValues = "('" + device_code + "','" + name + "','" + number + "','" + power + "','" + voltage + "','" + M_current + "','" + M_override + "','" + total_power + "')";
tempStrSQL = "insert into motor(device_code,name,number,power,voltage,M_current,M_override,total_power)Values" + sendValues;
SqlCommand cmd = new SqlCommand(tempStrSQL, con);
cmd.ExecuteNonQuery();
// DataAccess.UpdateDataBase(tempStrSQL);
}
}
MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK);
con.Close();
}
哪里出错了呢?编译也不会出错!急急急!各位高手帮帮忙! datagridview excel 数据库
[解决办法]
打断点,单步调试就知道了