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!
Related
I'm trying this code but it shows an error on da.Fill(dt)
No value given for one or more required parameters.
Why does it show that error? I clearly check all names of databases and tables and fields, they all are correct and I'm using date/time field for datetime.
Can you help me with this?
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb";
OleDbConnection ccc = new OleDbConnection(conn);
ccc.Open();
string css = "SELECT * from tbl3 Where dateitem between '" + dateTimePicker1.Value.ToString() + "%' AND '" + dateTimePicker2.Value.ToString()+"%'";
OleDbCommand non = new OleDbCommand(css, ccc);
OleDbDataAdapter da = new OleDbDataAdapter(non);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
As others have mentioned you should use the parameters instead of hard coding the values.
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb"))
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
var param1 = new OleDbParameter("#DateTimePicker1", OleDbType.DBDate); //you may have to play with different types
param1.Value = dateTimePicker1.Value;
cmd.Parameters.Add(param1);
var param2 = new OleDbParameter("#DateTimePicker2", OleDbType.DBDate);
param2.Value = dateTimePicker2.Value;
cmd.Parameters.Add(param2);
cmd.CommandText = "SELECT * from tbl3 Where datetime >= #DateTimePicker1 and datetime <= #DateTimePicker2";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
}
}
I am developing a C# windows application. I am trying to read excel file and to display column name as check box entity. I used the following code but can't display anything in the DataGridView.
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
for (int i = 0; i < dt.Columns.Count;i++)
{
DataColumn dc = dt.Columns[i];
CheckBox Ckb = new CheckBox();
Ckb.Name = dc.ToString();
dataGridView1.DataSource = dt.Columns[i].ToString();
}
}
}
I want the out put to look like the following :
Thanks
Why do you want to populate the DataGrid in a For Loop?
Before the For loop you can try this:
DataSet ds = new DataSet();
Oda.Fill(ds, "Table");
dataGridView1.DataSource = ds.Tables["Table"];
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.
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();
}
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.