Update an entire row in Excel using OleDB command - c#

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.

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!

Export multiple sheets in same Excel file using C#

I have two data tables and I want to export both data tables as an Excel file having two sheets containing the data of these two data tables.
string myquery = "select * from mytable";
string myquery2 = "select * from blatable";
--making and connection to my db--
try{
cnn.open();
MySqlCommand cmd = new MySqlCommand(myquery, cnn);
{
MySqlDataAdapter sda = new MySqlDataAdapter();
{
sda.SelectCommand = cmd;
mydt = new DataTable();
sda.fill(mydt);
}
}
MySqlCommand cmd1 = new MySqlCommand(myquery2, cnn);
{
MySqlDataAdapter sda = new MySqlDataAdapter();
{
sda.SelectCommand = cmd1;
mydt1 = new DataTable();
sda.fill(mydt1);
}
}
}
Have used SmartXLS for this matter sometime now and its easy to use. Its also fairly documented
http://www.smartxls.com/csharp/workbook.htm#vworkbook-rw-xlsx

Dataset filter method

Here is my code,
Conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(ds);
ds.Tables[0].DefaultView.RowFilter = " mst_remote_station_id Like'*9001*'";
Here I am getting Complete row for id 9001. I need only one column value for this id.
DataRow[] rows = ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
You can do it this way also if you need only one row just select it in the initial query.
Also you should Dispose the SqlDataAdapter after using it ! You can do it with using block
Conn.Open();
DataSet ds = new DataSet();
SqlCommand sqlCmd = new SqlCommand("SELECT * from CurrentDataCR ",Conn);
using(SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(ds);
}
ds.Tables[0].Select("mst_remote_station_id Like '%9001%'");
I don't know if the connection is global but it is bad practice to use global connection, you have connection pool so use separate connection for every query.

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();
}

C# Excel Read Problem

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.

Categories

Resources