Updating cell in excel using c# OLEDB connection - c#

I need your help with my problem:
I have a code here that updates cell in excel using c#. My problem is I have to open my excel file at first so that it can update the cell. What I need to do is update the cell without open the excel file before. Is it possible?
That's what I have so far:
private void WOupdate()
{
string WOExcel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\t-jjtabije\\Desktop\\WO And CAO Update.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text'";
string conStr, sheetName;
conStr = string.Empty;
//Get the name of the First Sheet.
using (OleDbConnection kuneksyon = new OleDbConnection(WOExcel07ConString))
{
using (OleDbCommand utos = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
utos.Connection = kuneksyon;
kuneksyon.Open();
DataTable dtExcelSchema = kuneksyon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
kuneksyon.Close();
utos.Connection = kuneksyon;
utos.CommandText = "UPDATE [" + sheetName + "] SET [LTE WO]= '" + Path.GetFileName(WOfilename) + "', [REFARM LTE BW]='" + WObw.ToString() + "', [WO Status-LTE]='" + WOstat.ToString() + "' WHERE SITEID= '" +WOsiteid.ToString()+ "'";
kuneksyon.Open();
MessageBox.Show(WOfilename + WOsiteid + WOservice + WObw + WOstat);
oda.SelectCommand = utos;
utos.ExecuteNonQuery();
kuneksyon.Close(); ;
}
}
}
}

Related

Error: ExecuteNonQuery: Connection property has not been initialized. (Trying to connect with Snowflake DB using script task of SSIS)

Requesting your help on below error.
Error: ExecuteNonQuery: Connection property has not been initialized.
I am trying to connect with snowflake DB using script task of SSIS using CSharp code. I have created the connection successfully in connection manager in SSIS and using same connection in C-Sharp code to perform some SQL operation on Snowflake DB. but getting above error in below line.
CreateTableCmd.ExecuteNonQuery();--- error coming on this code
Can somebody please help as I am new to C-Sharp. Also same code is working when change connection of Snowflake to SqlServer.
public void Main() {
string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
// string StartingColumn = Dts.Variables["User::StartingColumn"].Value.ToString();
// string EndingColumn = Dts.Variables["User::EndingColumn"].Value.ToString();
// string StartReadingFromRow = Dts.Variables["User::StartReadingFromRow"].Value.ToString();
var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();
//Declare and initilize variables
string fileFullPath = "";
//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "\\" + file.Name;
//Create Excel Connection
string ConStr;
string HDR;
HDR = "YES";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
//MessageBox.Show(TableName);
//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//string sheetname;
//sheetname = "";
//foreach (DataRow drSheet in dtSheet.Rows)
//{
//if (drSheet["TABLE_NAME"].ToString().Contains("$"))
//{
// sheetname = drSheet["TABLE_NAME"].ToString();
//Load the DataTable with Sheet Data so we can get the column header
//OleDbCommand oconn = new OleDbCommand("select top 1 * from [" + sheetname + StartingColumn + StartReadingFromRow + ":" + EndingColumn + "]", cnn);
OleDbCommand oconn = new OleDbCommand("select top 1 * from [Part_D_Cut_Points$]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();
int ColumnCount = dt.Columns.Count;
//Prepare Header columns list so we can run against Database to get matching columns for a table.
string ExcelHeaderColumn = "";
String SelectColumn = "";
//string GetHeader ColumnsList to Create Table= "";
for (int i = 0; i < dt.Columns.Count; i++)
{
String check = dt.Columns[i].ColumnName;
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "[" + dt.Columns[i].ColumnName + "] NVarchar(150) NULL" + ",";
else
ExcelHeaderColumn += "[" + dt.Columns[i].ColumnName + "] NVarchar(150) NULL";
}
//string GetSelect ColumnsList Fetch data from ExcelTable "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
SelectColumn += "[" + dt.Columns[i].ColumnName + "]" + ",";
else
SelectColumn += "[" + dt.Columns[i].ColumnName + "]";
}
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["SnowFlakeDB"].AcquireConnection(Dts.Transaction) as SqlConnection);
TableName = "STG_PART_D_CUT_POINTS_RAW";
string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]')";
CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
//CreateTableStatement += "([" + line.Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
CreateTableStatement += "(ID int IDENTITY(1,1),[FileName] Varchar(70) Null," + ExcelHeaderColumn + ")";
SqlCommand sqlCommand = new SqlCommand(CreateTableStatement, myADONETConnection);
SqlCommand CreateTableCmd = sqlCommand;
CreateTableCmd.ExecuteNonQuery();
//MessageBox.Show(CreateTableStatement);
//Use Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
//OleDbCommand oconn1 = new OleDbCommand("select"+ file.Name +" AS [FileName]," + SelectColumn + " from [" + sheetname + StartingColumn + StartReadingFromRow + ":" + EndingColumn + "]", cnn1);
OleDbCommand oconn1 = new OleDbCommand("select '" + file.Name + "' AS [FileName]," + SelectColumn + " from [Part_D_Cut_Points$]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(myADONETConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
//}
//}
}
}
The IF EXISTS (SELECT * FROM sys.objects... statement is not valid SQL in Snowflake. Closest equivalent would be CREATE OR REPLACE TABLE...

C# Importing in SSIS Visual Studio Excel sheet name with blank spaces

When reading the excel sheets, the ones with spaces in their sheet names are throwing errors when executing the script.
It seems that the solution is in this select * from [" + sheetname + "]". But none of the examples resulted in a correct solution when for example removeing the brackets or changing the double quote by a simple quote.
Is sheetname.replace(" ", "_") the only way I see to be able to select the sheets with a blank space?
PS: when I remove the blank space in the source file and replace it with "_", the script is running fine. But unfortunately, I cannot be doing this manually.
Thank you
> OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
This is the whole code I have in Visual Studio.
namespace ST_689a7e5f91cd44f892e3d4b3290d003b
{
public void Main()
{
// TODO: Add your code here
String FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();
//Declare and initilize variables
string fileFullPath = "";
//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "";
fileFullPath = FolderPath + "\\" + file.Name;
filename = file.Name.Replace(".xlsx", "");
MessageBox.Show(fileFullPath);
//Create Excel Connection
string ConStr;
string HDR;
HDR = "YES";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
OleDbConnection cnn = new OleDbConnection(ConStr);
//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
//Display Sheet Name , you can comment it out
MessageBox.Show(sheetname);
//Load the DataTable with Sheet Data sheetname = Regex.Replace(input, #"[^0-9a-zA-Z\._]", string.Empty);
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
//cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
//drop $from sheet name
sheetname = sheetname.Replace("$", "");
// Generate Create Table Script by using Header Column,It will drop the table if Exists and Recreate
string tableDDL = "";
tableDDL += "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = ";
tableDDL += "OBJECT_ID(N'[dbo].[" + filename + "_" + sheetname + "]') AND type in (N'U'))";
tableDDL += "Drop Table [dbo].[" + filename + "_" + sheetname + "]";
tableDDL += "Create table [" + filename + "_" + sheetname + "]";
tableDDL += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)" + ",";
else
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)";
}
tableDDL += ")";
//use ADO.NET connection to Create Table from above Definition
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
//you can comment the messagebox, it is for debugging
MessageBox.Show(tableDDL.ToString());
SqlCommand myCommand = new SqlCommand(tableDDL, myADONETConnection);
myCommand.ExecuteNonQuery();
//Comment this message, it is for debugging
MessageBox.Show("TABLE IS CREATED");
//Load the data from DataTable to SQL Server Table.
SqlBulkCopy blk = new SqlBulkCopy(myADONETConnection);
blk.DestinationTableName = "[" + filename + "_" + sheetname + "]";
blk.WriteToServer(dt);
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}

C# SQLite Database During Update

My SQLite query hangs then locks during my ExecuteNonQuery() in WriteToDB() below. It only seems to lock during the UPDATE and has no problem with the INSERT. This is only running in a single thread. When it hangs, I can see the journal being created in the SQLite database directory as if it keeps trying to write. It throws a SQLiteException with ErrorCode=5, ResultCode=Busy.
public String WriteToDB()
{
String retString = "";
//see if account exists with this email
String sql = "";
bool aExists = AccountExists();
if (!aExists)
{
sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
retString = "Added account";
}
else
{
sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
retString = "Updated account";
}
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
}
}
return retString;
}
//Test to see if Email exists as account
public bool AccountExists()
{
int rCount = 0;
String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
}
}
if (rCount > 0)
return true;
return false;
}
Oh man I feel dumb. I thought I posted all relevant code but all the code I posted works just fine. I had:
SQLiteDataReader dbReader = sqlcmd.ExecuteReader()
instead of
using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())
In another function. I thought it was an issue with the UPDATE because that was the place where the lock took place. Thanks for the responses and hopefully this reminds reminds everyone to use using() blocks with SQLite the first time!

How Load Excel File With Password In C#

I Work On C# Project
I Use Below Code For Import XLS Or XLSX File On DataSet.
public static DataSet ImportExcelXLS(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(
OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow schemaRow in schemaTable.Rows)
{
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
try
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
sheet = sheet.Replace("$", "");
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
catch (Exception ex)
{
throw new Exception(ex.Message + string.Format("Sheet:{0}.File:F{1}", sheet, FileName), ex);
}
}
}
}
return output;
}
This Code Work Correctly For Load Excel File Without Password. But When Run For Load a File With password Show Under error:
Cannot start your application. The workgroup information file is
missing or opened exclusively by another user.
Now How Change My Code For Load Encrypt File?
Please : use this lib:
using Microsoft.Office.Interop.Excel
Please , provide password :
WorkbookObject.Password = password;
Please, Change ConnString:
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Password=password;Extended Properties='Excel 8.0;HDR=YES'";
Here, your answer is:
if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Password=password;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Password=password;Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}
Try for this code:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Password=password;Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
but still the exception popped:
Cannot start your application. The workgroup information file is missing or opened exclusively by another user.

Access database not updating

I am trying to connect to access 2010 database using the following string connection. But, it wont make any changes in the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:\\Program Files\\LogEntry\\LogEntry.accdb; Persist Security Info = False;");
conn.Open();
String text2send = "INSERT INTO TLC(Name,Department,Position,VisitDate,InTime,OutTime,Purpose,HelpedBy,Campus,HelpCode) VALUES(" + name + "," + department + "," + position + "," + date + "," + hourIn + "," + hourOut + "," + purpose + "," + helpedBy + "," + campus + "," + helpcode + ");";
OleDbCommand cmd = new OleDbCommand(text2send,conn);
conn.Close();
Edit:
This is the edited code that I used with Parameter query.
String name = nameTextbox.Text;
String department = departmentCBox.Text;
String purpose = purposeTextbox.Text;
String position = positionCBox.Text;
String date = inDate.Value.ToString("MM/dd/yyyy");
String helpCode = helpCodeCBox.Text;
String hourOut = ""+OutHour.Text+":"+OutMin+" "+OutMeredian;
String helpedBy= "";
String campus= "";
String helpcode= "";
String hourIn = "" + DateTime.Now.ToString("hh") + ":" +
DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt");
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:\\Program Files\\LogEntry\\LogEntry.accdb; Persist Security Info = False;");
conn.Open();
String text2send = "Insert Into TLC([Name],[Department],[Position],[VisitDate],[InTime],[OutTime],[Purpose],[HelpedBy],[Campus],[HelpCode]) VALUE(?,?,?,?,?,?,?,?,?,?);";
OleDbCommand cmd = new OleDbCommand(text2send,conn);
cmd.Parameters.AddWithValue("Name", name);
cmd.Parameters.AddWithValue("Department", department);
cmd.Parameters.AddWithValue("Position", position);
cmd.Parameters.AddWithValue("Purpose", purpose);
cmd.Parameters.AddWithValue("HelpedBy", helpedBy);
cmd.Parameters.AddWithValue("Campus", campus);
cmd.Parameters.AddWithValue("HelpCode", helpcode);
cmd.ExecuteNonQuery();
conn.Close();
add cmd.ExecuteNonQuery(); after your command is created and before you close the connection

Categories