Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query excel sheet in c#

I want to read Excel file in c# using following code

string excelFileName = "Book2.xls";
string excelConnectString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Book2.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
//string excelConnectString = @"Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0; HDR=Yes;IMEX=1";

OleDbConnection objConn = new OleDbConnection(excelConnectString);
OleDbCommand objCmd = new OleDbCommand("Select * From [Sheet1$]", objConn);

OleDbDataAdapter objDatAdap = new OleDbDataAdapter();
objDatAdap.SelectCommand = objCmd;
DataSet ds = new DataSet();
objDatAdap.Fill(ds);

enter image description here

Everything is working fine.Now my requirement is to read the excel file something like below

SELECT A,B,D From [Sheet1];
like image 610
santosh singh Avatar asked Jul 22 '11 11:07

santosh singh


3 Answers

The Select-command should look like this if you want to read A1 to D1:

SELECT * FROM [SHEETNAME_HERE$A1:D1]

Whole Code:

OleDbConnection con = new OleDbConnection(
    "provider=Microsoft.Jet.OLEDB.4.0;data source="
    + XLS_FILE_NAME_AND_PATH_HERE
    + ";Extended Properties=Excel 8.0;");

StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("SELECT * FROM [" + SHEETNAME_HERE + "$A1:D1]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);

DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);

DataView dvEmp = new DataView(dsXLS.Tables[0]);

dataGridView1.DataSource = dvEmp;
like image 97
MariusK Avatar answered Oct 04 '22 15:10

MariusK


DataTable Contents = new DataTable();
using (OleDbDataAdapter adapter = new OleDbDataAdapter("Select * From [Sheet1$]", objConn))
{
    adapter.Fill(Contents);
}
Console.WriteLine(Contents.Rows[0][0]);

You can select a particular cell by passing the proper index.

like image 45
NaveenBhat Avatar answered Oct 04 '22 17:10

NaveenBhat


You can just constuct use query like that:

SELECT FirstName, LastName, Mobile FROM [Sheet1$]

i.e. use first row values as column names.

like image 40
Petr Abdulin Avatar answered Oct 04 '22 15:10

Petr Abdulin