user3328870
user3328870

Reputation: 361

Import data from excel into DataGridview with specific condition

This is how i am import my Excel file:

stirng file = "c:\myFile.xlsx";
DataGridView dgvIM;

private void Import()
        {
            String name = "Items";
            String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                            file +
                            ";Extended Properties='Excel 8.0;HDR=YES;';";

            OleDbConnection con = new OleDbConnection(constr);
            OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
            con.Open();

            OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
            System.Data.DataTable data = new System.Data.DataTable();
            sda.Fill(data);
            dgvIM.DataSource = data;
        }

What i want to do is import my Excel file but with specific condition, my second column contain several groups of strings ("First", "Second" etc..) and i want to add only the column with name "First" and not the whole list.

How can i do that ?

Upvotes: 0

Views: 1980

Answers (1)

Steve
Steve

Reputation: 216343

Just use a where condition on the sql command like this

string cmdText = "Select * From [" + name + "$] WHERE secondColumnName = 'First'";
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand oconn = new OleDbCommand(cmdText con))
{
     con.Open();
     OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
     System.Data.DataTable data = new System.Data.DataTable();
     sda.Fill(data);
     dgvIM.DataSource = data;
}

Note that in your connectionstring you specify HDR=YES, this means that the first non blank line of your excel sheet contains headers that are interpreted as column names. You should update your query setting the correct column name in the WHERE condition

EDIT In response at your comments below, if you want to retrieve every row where AGE is 12 the query becomes

string cmdText = "Select * From [" + name + "$] WHERE Age = 12";

Upvotes: 2

Related Questions