Thursday, January 6, 2011

Import Excel using OLEDB

You may need to impor a namespace:
using System.Data.OleDb;

//New DataTAble
table = new DataTable();

//Conection Straig For Excel Files
//FilePath is the direccion where the file is stored
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + FilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";

//Establish Coneccion
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.Connection = conn;

//Query for the Sheet
//Hoja is the name of the sheet
comm.CommandText = "SELECT * FROM ["+ Hoja +"$]";

//Execute Query and stores in a DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = comm;
adapter.Fill(table);
conn.Close();

//Then you can put the informacion in a grid
//MyGrid.DataSource = table
//Or take the table and insert into a databases

No comments:

Post a Comment