When importing any kind of data into an application simply using a text file is sometimes not sufficient, especially if the users already have information in an Excel file. Using an Excel file in C# is like connecting to a database. You provide a connection string (which, among other things, include the file path) and use SQL statements to read the file. The following snippet of code connects an Excel file to a DataGridView form component. OleDbConnection connection = new OleDbConnection(Provider=Microsoft.Jet.OLEDB.4.0;Data Source=foo.xls;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";); try { connection.Open(); OleDbCommand cmd = connection.CreateCommand(); cmd.CommandText = "SELECT * FROM [Sheet1$]"; DataSet dataSet = new DataSet(); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmd); dataAdapter.Fill(dataSet, "ImportData"); dataGridView_Sheet1.DataSource = dataSet.Tables["ImportData"].DefaultView; } ...
A blog about software development and architecture. The main focus is .NET and Open Source.