更新datagridview用作数据库excel文件

时间:2017-02-11 20:01:56

标签: c# excel datagridview updates oledbconnection

我使用excel将数据添加到datagridview。我不知道如何在datagridview中进行所有修改时使用update函数。

excel的表格很简单 ID,材料描述,制造商,制造商零件编号供应商,供应商零件编号,数量,位置

        String name = "Sheet1";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "test.xlsx" +
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        con.Open();
        OleDbCommand oconn = new OleDbCommand("Update [" + name + "$]", con);
        con.Close();

我试过这个,没有结果:

            System.Data.OleDb.OleDbConnection MyConnection;
            System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
            string sql = null;
            MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='test.xlsx';Extended Properties=Excel 8.0;");
            MyConnection.Open();
            myCommand.Connection = MyConnection;
            sql = "Update [Sheet1$] set id = '?' where id=?";
            myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
            MyConnection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

1 个答案:

答案 0 :(得分:0)

  

尝试这样的事情:

    private void UpadateButton_Click(object sender, EventArgs e)  {
        tran = null;
        excelConnection = new OleDbConnection(connectionString);
        excelConnection.Open(); // This code will open excel file.
        strSQL = "Update [Sheet1$] set Manufacturer= '" + dgvExcelList["Manufacturer",dgvExcelList.CurrentRow.Index].Value.ToString() + "' WHERE ID = '" + dgvExcelList["ID",dgvExcelList.CurrentRow.Index].Value.ToString() + "'";
        try
        {
            tran = excelConnection.BeginTransaction();
            dbCommand = new OleDbCommand(strSQL, excelConnection);
            dbCommand.ExecuteScalar();
            tran.Commit();
        }
        catch(OleDbException ex)
        {
            tran.Rollback();
            MessageBox.Show("error:transaction rolled back," + ex.Message);
        }