C# Excel Read Problem - c#

my excel
|Name|Telephone|
|Color|Car|
|John|Jon|
i need "|John|Jon|" how to select OleDbCommand? third row start
My Csharp Not Work Code:
ExcelCommand.CommandText = #"SELECT * FROM " + SpreadSheetName + " Where RowNumber > 3";
Thank you...

This worked for me. You can change the SELECT statement as you wish (specific rows, multiple columns, ...) to get a single result or a set of rows returned.
string connectionString = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=test.xls;";
connectionString += "Extended Properties=Excel 8.0;";
OleDbConnection con = new OleDbConnection(connectionString);
DataSet ds = new DataSet("stuff");
OleDbDataAdapter adapter = new OleDbDataAdapter();
// adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$A1:A100];", con);
// adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$];", con);
adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$] where [A] = 'John';", con);
adapter.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach (DataColumn dc in ds.Tables[0].Columns)
{
Console.WriteLine(dr[dc].ToString());
}
}

May be instead "RowNumber > 3" use "RowNumber = 3". "|John|Jon|" - third row.

Related

Read Excel named range from C#

I am trying to read a named range from my excel as per below:
conn.Open();
using (OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [NamedRange]"))
{
cmd1.Connection = conn;
//conn.Open();
var result = cmd1.ExecuteReader();
while (result.Read())
{
var str = result[0].ToString();
}
}
The code runs but the while loop gets skipped. I know my named range should be read because this method works:
OleDbDataAdapter da2 = new OleDbDataAdapter("Select * from [NamedRange]”, conn);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
foreach (DataColumn Col in dt2.Columns)
{var str = Col.Caption}
I cannot figure out why the first method does not work.
For everyone who is still looking for a solution, change your query like this:
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [sheetName$][NamedRange]")
I hope this helps!

Error when retrieving data from database (ado.net)

I'm getting an error when retrieving data from the child row. Basically I need the lecturerName from tbl_lecturer, projectTitle from tbl_lecturer_project.
Here is my code.
//get data from 3 tables
DataSet ds = new DataSet(); // .xsd file name
DataTable dt = new DataTable();
//Connection string replace 'databaseservername' with your db server name
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapter;
con.Open();
//Stored procedure calling. It is already in sample db.
string selectSQL = "SELECT * FROM tbl_allocated_project where allocatedGroupId='" + team + "'";
cmd = new SqlCommand(selectSQL, con);
ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "tbl_allocated_project");
cmd.CommandText = "SELECT * FROM tbl_lecturer_project";
adapter.Fill(ds, "tbl_lecturer_project");
cmd.CommandText = "SELECT * FROM tbl_lecturer";
adapter.Fill(ds, "tbl_lecturer");
DataRelation dr1 = new DataRelation("dr1", ds.Tables["tbl_lecturer"].Columns["lecturerId"],ds.Tables["tbl_lecturer_project"].Columns["lecturerId"]);
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]);
ds.Relations.Add(dr1);
ds.Relations.Add(dr2);
foreach (DataRow row in ds.Tables["tbl_allocated_project"].Rows)
{
lblDisplay.Text = "";
//lblDisplay.Text += row["allocatedGroupId"];
//lblDisplay.Text += " " + row["intro"];
foreach (DataRow col in row.GetChildRows(dr2))
{
DataRow rowdata = col.GetParentRows(dr1)[0];
//lblDisplay.Text += " ";
lblDisplay.Text += rowdata["projectTitle"];
}
}
I'm getting this error:
GetChildRows requires a row whose table is tbl_lecturer_project, but the specified row's table is tbl_allocated_project.
Please help.
Should this:
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], ds.Tables["tbl_allocated_project"].Columns["allocatedProjectId"]);
be this:
DataRelation dr2 = new DataRelation("dr2", ds.Tables["tbl_allocated_project"].Columns["lecturerProjectId"], ds.Tables["tbl_lecturer_project"].Columns["allocatedProjectId"]);
This would make tbl_allocated_project the parent of tbl_lecturer_project, which should allow you to call GetChildRows on it.

Update an entire row in Excel using OleDB command

I am trying to blankout/clear an entire excel tab. But nothing seems to work
I tried the following approach:
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);
OleDbCommand count = new OleDbCommand("Select count(*) FROM [Sheet1$]", connection);
DataSet dataset = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("Select * from [Sheet1$]", connection);
adapter.Fill(dataset);
for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
{
DataRow dtRow = dataset.Tables[0].Rows[i];
foreach (DataColumn col in dataset.Tables[0].Columns)
{
if(col.DataType == typeof(string))
dataset.Tables[0].Rows[i][col] = "";
}
}
dataset.Tables[0].AcceptChanges();
adapter.Update(dataset.Tables[0]);
If your Excel file has primary key,you can use OleDbCommandBuilder,if not, OleDbDataAdapter or OleDbCommand will be a better way.adapter.you can't directly use Update(dataset.Tables[0]),here is the code:
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", myConnection);
DataTable dt = new DataTable();
adapter.Fill(dt);
string updateSQL = string.Format(#"UPDATE [Sheet1$] SET Status =? WHERE ID IN ( SELECT TOP 5 ID FROM [Sheet1$] WHERE Status <>? OR Status IS NULL )");
adapter.UpdateCommand = new OleDbCommand(updateSQL, myConnection);
adapter.UpdateCommand.Parameters.Add("#Status", OleDbType.Char, 255).SourceColumn = "Status";
adapter.UpdateCommand.Parameters.Add("#OldStatus", OleDbType.Char, 255, "Status").SourceVersion = DataRowVersion.Original;
dt.AsEnumerable().Take(5).ToList().ForEach(o => o.SetField("Status", #"Imported"));
dt.AcceptChanges();
adapter.Update(dt);
I guess to manipulate excel file, NPOI is a better option for you.
It's open source & easy to use.
I used OLEDB to read excel file before, but never try to use it updating data. If you have to use it, make sure your excel file is not readony.

How to insert a row using a IDbDataAdapter(SqlDataAdapter or OleDbDataAdapter) without loading the entire table?

I need to insert a row into a DataTable using a OleDbDataAdapter. However, my table has more than 100000 records and I don't want to load all the records.
My current code loads all the records into the DataTable
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Is there a way to insert data into my table without filling my datatable with all the rows other than adding "where 1 = 0" to my statement
EDIT
I need to use a DataAdapter to do this
Call FillSchema instead of Fill
As per request:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Yes, by using the DbCommand class to execute an INSERT.
Your code will probably look something like
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
var query = "INSERT INTO Nodes (nID, csNumber) " +
"VALUES (?, ?)";
var command = new OleDbCommand( query, connection);
command.Parameters.AddWithValue("#nID", nNodeID);
command.Parameters.AddWithValue("#csNumber", strNumber);
connection.Open();
command.ExecuteNonQuery();
}
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
try
oleconnStkNames = new OleDbConnection(strAccessConnectionString);
oleconnStkNames.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oleconnStkNames; //new OleDbConnection(strAccessConnectionString);
cmd.CommandText = "TheName of your InsertQuery "; // name of the query you want to run
cmd.CommandType = CommandType.StoredProcedure; // or System.Data.CommandType.Text if you are not using a Access StoredProc
OleDbDataReader rdr = cmd.ExecuteReader();
catch (Exception ex)
{
bla..bla..bla
}
//if you want to wrap it in a using() and add transactional processing use this example that I've written to fit what ever it is you are doing..
using (OleDbCommand olecmdStkNames = new OleDbCommand(strSQL, oleconnStkNames))
{
olecmdStkNames.CommandTimeout = 60;
oletransStockList = oleconnStkNames.BeginTransaction();
olecmdStkNames.Transaction = oletransStockList;
olecmdStkNames.CommandType = System.Data.CommandType.Text;
try
{
intRecordsAffected = olecmdStkNames.ExecuteNonQuery();
oletransStockList.Commit();
}
catch (OleDbException oledbExInsert_Update)
{
oletransStockList.Rollback();
Console.WriteLine(oledbExInsert_Update.Message);
}
((IDisposable)oletransStockList).Dispose();
}

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);
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.

Categories

Resources