从OleDbDataReader获取值

时间:2014-08-21 16:13:24

标签: c# excel oledbdatareader

我想知道是否可以从OleDbdataReader检索特定值。

例如,我从excel表导入数据,该表包含100行和10列。然后我希望读者从指定行的所有列中获取值。假设我有一个文本框,将随机数放入其中(85),读者在第一列中找到该数字并相应地读取所有列值。

而且,是的,如果有可能的话,请你就如何做到这一点提供一些指导。

到目前为止,我只是设法让读者阅读所有的值。

主要思想是通过改变文本框中的值,读者可以将不同的值集应用于方法中。从excel表链接到图片以使其更清晰:

https://imagizer.imageshack.us/v2/505x318q90/743/YIVGVf.jpg

    private void button1_Click(object sender, EventArgs e)
    {
        Model ThisModel = new Model();
        Beam ThisBeam = new Beam();

        OleDbConnection conn = new OleDbConnection();
        const string excelConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=@1;";
        const string connStringExtras = @"Extended Properties=""Excel 8.0;HDR=Yes;Imex=1""";
        conn.ConnectionString = excelConnString.Replace("@1", "C:\\Users\\Andrejs\\Desktop\\API2.xls;") + connStringExtras;

        try
        {
            conn.Open();
            OleDbCommand cmd = new OleDbCommand("SELECT A, B, C, D, E, F "+
                "FROM [SHEET1$]", conn);
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                double X = (double)reader.GetValue(1);
                double Y = (double)reader.GetValue(2);
                CreatePadFooting(X, Y);
            }
        }
            catch
            {
            }

        ThisModel.CommitChanges();
    }
    private static void CreatePadFooting(double X, double Y)
    {
        Beam PadFooting1 = new Beam();

        PadFooting1.Name = "FOOTING";
        PadFooting1.Profile.ProfileString = "200*200";
        PadFooting1.Material.MaterialString = "K30-2";
        PadFooting1.Class = "8";
        PadFooting1.StartPoint.X = X;
        PadFooting1.StartPoint.Y = Y;
        PadFooting1.StartPoint.Z = 0.0;
        PadFooting1.EndPoint.X = X;
        PadFooting1.EndPoint.Y = Y;
        PadFooting1.EndPoint.Z = -500.0;
        PadFooting1.Position.Rotation = Position.RotationEnum.FRONT;
        PadFooting1.Position.Plane = Position.PlaneEnum.MIDDLE;
        PadFooting1.Position.Depth = Position.DepthEnum.MIDDLE;

        PadFooting1.Insert();
    }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要If语句来比较第一列的值,然后从Reader中读取。插入这样的If语句:

double randomValue = Convert.ToDouble(txtBoxRandomValue.Text); //get value to match and convert to double

try
    {
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("SELECT A, B, C, D, E, F "+
            "FROM [SHEET1$]", conn);
        OleDbDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {

        if (randomValue == Convert.ToDouble(reader.GetValue(0))) //checking here the first column
         {
            double X = (double)reader.GetValue(1);
            double Y = (double)reader.GetValue(2);
            CreatePadFooting(X, Y);
         }
       }
    }
        catch
        {
        }