Query excel sheet in c# - 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);
Everything is working fine.Now my requirement is to read the excel file something like below
SELECT A,B,D From [Sheet1];

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;

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.

You can just constuct use query like that:
SELECT FirstName, LastName, Mobile FROM [Sheet1$]
i.e. use first row values as column names.

Related

Join two DataTable one from excel data and other from text file to display it in datagridview in c#

I want to show data in datagridview in c# using from two source one from excel sheet and other from text file .I want to join these data source .For example if I get columns from Excel sheet excel1 excel2 AND Txt1 Txt2 from text file .Then I want to show result like excel1 excel2 Txt1 Txt2 in data grid view.
Current i can show data from excel file using below code.
private void button_cars_Click(object sender, EventArgs e)
{
String name = "Car List";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "c:\\Vehicle_List.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select CARID, BRAND, MODEL, FUEL, CC, YEAR From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridViewMain.DataSource = data;
}
I handle this situation like this
public DataTable mergeSheetAndTextFile()
{
String name = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"D:\\YOURPATH\\List.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select col1,col2 From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
data.Columns.Add("Txt1Col", typeof(System.String));
string[] txtFileLines= File.ReadAllLines("c://YOURPATH//test.txt");
int count=0;
foreach (DataRow row in data.Rows)
{
if(count<txtFileLines.Length){
row["Txt1Col"]=txtFileLines[count]
count++;`enter code here`
}
}
}

change datatable encoding NON ASCII to Unicode in c#

I have a table in foxpro 2.6 dos version and convert it to a datatable. so far so good. but some character do not display, fields that contain some non_ASCII character. how can i change codepage of a datatable to show all character?
public DataTable GetDataTableDBF(string FN)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetFullPath(FileNameStr).Replace(System.IO.Path.GetFile‌​Name(FN), "") + ";Extended Properties=dBASE IV;");
conn.Open();
string sQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(FN) + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sQuery, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.Tables[0];
}

Excel OleDb C# - Cannot select range if worksheet has special characters

I have run into a snag when reading info from a workbook in excel that contains a "#" in the name of the sheet. I am able to select the WHOLE worksheet but not a range in the worksheet.
Code:
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = "C:/TestExcel/TestWorkbook.xlsm";
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [Sheet #1$A1:A22]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
And the following queries work just fine.
comm.CommandText = "Select * from [Sheet #1$]";
comm.CommandText = "Select * from [Sheet2$A1:A22]";
I get the following exception saying it cannot find the table in question.
The Microsoft Office Access database engine could not find the object 'Sheet .1$A1:A22'.

Retrieve Column By Header Name

I am using OLEDB to read the data from an Excel spreadsheet.
var connectionString =
string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "mySheet");
var data = ds.Tables["mySheet"].AsEnumerable();
foreach (var dataRow in data)
{
Console.WriteLine(dataRow[0].ToString());
}
Instead of passing an index to the DataRow to get the value of a column, is there anyway to retrieve the column by the name of the column header?
Try this code:
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0; HDR=YES", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "mySheet");
var data = ds.Tables["mySheet"].AsEnumerable();
foreach (DataRow dataRow in data)
{
Console.WriteLine(dataRow["MyColumnName"].ToString());
Console.WriteLine(dataRow.Field<string>("MyColumnName").ToString());
}
I added in 2 ways to access the data in the row via column Name.
Hope this does the trick!!
Modify your connection string to specify that you have headers in your excel file.
You can do this by setting the HDR value.
Refer this link to for various variations of connection string and build the one that suits your needs"
http://www.connectionstrings.com/excel/
Use a DataTable to have your data.
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + **EXCEL FILE PATH** + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbCommand cmd2 = new OleDbCommand("SELECT * FROM [**YOUR SHEET** $]", conn);
cmd2.CommandType = CommandType.Text;
DataTable outputTable2 = new DataTable("myDataTable");
new OleDbDataAdapter(cmd2).Fill(outputTable2);
foreach(Datarow row in outputTable2)
{
String s = row["yourcolumnheader"].ToString();
}

Get column name from excel worksheet

In C#, how do I get the column name from a worksheet in an Excel file?
Here is my code so far:
ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", "#"C:\file.xlsx");
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM ["xlWorksheet"$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1);
objConn.Close();
Does you connection string include the HDR=YES ?:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
Once you populate your DataTable or DataSet you can treat the usual way:
dt.Columns[0].ColumnName
Or:
// For each DataTable, print the ColumnName.
foreach(DataTable table in dataSet.Tables)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(column.ColumnName);
}
}
Also this does not look syntax correct:
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM ["xlWorksheet"$]", objConn);
Should be something like:
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + xlWorksheet + "$]", objConn);
Finally, if you time - investigate EPPlus (open source) for reading/writing Excel - http://epplus.codeplex.com as it works in both 32-bit and 64-bit environments.

Categories

Resources