0

我的excel模拟需要导入C#,之后表格需要能够刷新。模拟围绕随机生成的数字展开。随机数是唯一改变的列,因为我是手动进行的。周围的列应使用随机数进行更新。我已经尝试了各种各样的东西,但到目前为止还没有运气。

此外,就像现在的代码一样,

adp.Update(excelDataSet);

命令调用错误“当传递带有修改行的 DataRow 集合时,更新需要有效的 UpdateCommand。” 该表仅在注释掉时才加载到gridview中。

这是我的代码atm。提前致谢。

            string fileName = @"C:\simulation.xlsx";
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
            OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
            con.Open();
            OleDbCommand selectCommand = new OleDbCommand("select * from [SHEET1$]", con);             
            OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
            adp.SelectCommand = selectCommand;
            DataSet excelDataSet = new DataSet();
            adp.Fill(excelDataSet);

            for (int i = 0; i < 29; i++)
            {
                excelDataSet.Tables[0].Rows[i][1] = Math.Round(r.NextDouble(), 2);
                excelDataSet.Tables[0].Rows[i][6] = Math.Round(r.NextDouble(), 2);
                excelDataSet.Tables[0].Rows[i][8] = Math.Round(r.NextDouble(), 2);
            }
            adp.Update(excelDataSet);
            gridview.DataSource = excelDataSet.Tables[0];
            con.Close();
4

1 回答 1

0

添加构建OleDbCommandBuilder的行

....
OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter();
adp.SelectCommand = selectCommand;
OleDbCommandBuilder cb = new OleDbCommandBuilder(adp);
adp.UpdateCommand = cb.GetUpdateCommand();
....

这将为UpdateCommand您在 OleDbDataAdapter 中创建 (也可用于InsertCommandand DeleteCommand

于 2013-10-22T22:30:36.487 回答