user1565774
user1565774

Reputation: 23

Import excel header data in a drop down in .net

Hi I am importing a excel or a .csv file using OpenFileDialog in Visual Studio 2005. I need to show all the headers in a list, which is supposed to be listed on a ComboBox.

e.g If I import a file which has 10 columns in it, my drop down should show me 10 values as 1, 2, 3..........10

Please let me know how to go about it.

Upvotes: 0

Views: 1229

Answers (2)

Zolfaghari
Zolfaghari

Reputation: 1323

// first read *.xls file into a DataTable; don't wory it is very quick.
public DataTable ReadExcelFile(string strFilePath)
{
    string sConnectionString  = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + "; Extended Properties=\"Excel 8.0; HDR=No; IMEX=1;\"";
    OleDbConnection objConn = new OleDbConnection(sConnectionString);
    objConn.Open();
    DataTable sdt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    // Change this part to read 1 row    
    String str = "SELECT TOP(2) * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
    //String str = "SELECT * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
    OleDbCommand objCmdSelect = new OleDbCommand(str, objConn);
    OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
    objAdapter1.SelectCommand = objCmdSelect;
    DataTable dt = new DataTable();

    objAdapter1.Fill(dt);

    objConn.Close();
    dt.AcceptChanges();

    return dt;
}

Now working with DataTable

DataTable dt = ReadExcelFile(@"c:\\x.xlsx");
if (dt != null)
{
    System.Windows.Forms.ComboBox cmb = new System.Windows.Forms.ComboBox();
    for (int i = 0; i < dt.Columns.Count; i++)
        cmb.Items.Insert(i, dt.Columns[i].ColumnName);
}

Upvotes: 0

T McKeown
T McKeown

Reputation: 12857

CSV is completely different animal than Excel.

I would use the OpenXml library OR use the OleDb driver to read from the excel file.

Look here: Reading excel file using OLEDB Data Provider

You will need to have the ACE driver installed, you may already have it though.

Upvotes: 1

Related Questions