根据列Value从excel获取Row值

时间:2014-06-17 08:20:58

标签: c# excel oledb

我正在尝试根据列值从excel表中获取Row值。 例如我有CutsomerID,比方说5,所以我想要名字5,姓氏5和地址5

enter image description here

我正在将整个Excel工作表转换为DataTable然后尝试读取每个DataRow,当我将CustomerID设置为5时,我复制所有值并从循环中断 这是我的代码,它也运行良好,但我想知道有没有办法优化它。

这是我的代码。

public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)    
{
   OleDbConnectionStringBuilder connectionStringBuilder = new  OleDbConnectionStringBuilder();
   connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
   connectionStringBuilder.DataSource = excelFilePath;
   connectionStringBuilder.Add("Mode", "Read");

   const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
   connectionStringBuilder.Add("Extended Properties", extendedProperties);

   String connectionString = connectionStringBuilder.ToString();
   // Create connection object by using the preceding connection string.
   using( var objConn = new OleDbConnection(connectionString))
   {
        objConn.Open();

        // Get the data table contaning the schema guid.
        DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (excelSheetsDataTable == null)
              return null;

        // get all the tables in the Sheet
        List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();

          // Our data is on First sheet only
                OleDbCommand _oleCmdSelect = new OleDbCommand(@"SELECT * FROM [" + excelSheets[0] + "]", objConn);
                OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
                oleAdapter.SelectCommand = _oleCmdSelect;

                DataTable newDataTable = new DataTable();
                oleAdapter.FillSchema(newDataTable, SchemaType.Source);
                oleAdapter.Fill(newDataTable);

                if (newDataTable.Columns.Contains("CustomerID"))
                {
                    foreach (DataRow rowValue in newTB.Rows)
                    {
                        if ((string) rowValue["CustomerID"] == customerID)
                        {
                            var data = new ExcelData
                            {
                                customerFirstName = rowValue["Customer_First_ Name"].ToString(),
                                customerLastName = rowValue["Customer_Last_Name"].ToString(),
                                customerAddress = rowValue["Customer_Address"].ToString(),
                            };
                            return data;
                        }
                    }
                    String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
                    MessageBox.Show(message);
                }
                else
                {
                    String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
                       MessageBox.Show(message);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return null;
    }


public class ExcelData
{
    public String customerID;
    public String customerFirstName;
    public String customerLastName;
    public String customerAddress;
}

2 个答案:

答案 0 :(得分:0)

礼貌msdn网站:

链接:MSDN

DataTable dt;
    private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            openFileDialog1.ShowDialog();
            string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
            var con = new OleDbConnection(connectionString);
            var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=@c", con);
            cmd.Parameters.Add("@c", "33264");
            con.Open();
            var dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                dt = new DataTable();
                dt.Load(dr);
            }
            dr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            DataGridView dv = new DataGridView();
            this.Controls.Add(dv);
            dv.DataSource = dt;
        }

    }

修改 根据您的代码,您应该尝试以下代码行:

OleDbCommand _oleCmdSelect = new OleDbCommand(@"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = @custID"  , objConn);
    _oleCmdSelect.Parameters.Add("@custID", customerID);
    OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
    oleAdapter.SelectCommand = _oleCmdSelect;

答案 1 :(得分:0)

将您的select查询更改为以下内容 -

@"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"