Update Specified Fields in Existing Excel File using C# .NET (.XLS) Format
I Just Want to update Existing Excel File using C# .NET (.XLS) Format
This code is working fine Thanks
String sConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newFile + ";Extended Properties='Excel 8.0;HDR=NO'";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter xlAdapter = new OleDbDataAdapter();
xlAdapter.SelectCommand = selectCmd;
DataSet xlDataset = new DataSet();
xlAdapter.Fill(xlDataset, "XLData");
xlAdapter.Dispose();
selectCmd.Dispose();
var thisDates = fDate.ToString("dd/MM/yyyy").Trim() + " TO " +
tDate.ToString("dd/MM/yyyy").Trim();
OleDbCommand cmdUpDates = new OleDbCommand("UPDATE [Sheet1$C5:C5] SET F1='" + thisDates + "'", objConn);
cmdUpDates.ExecuteNonQuery();
cmdUpDates.Dispose();
var totalRows = xlDataset.Tables[0].Rows.Count;
for (int z = 0; z < totalRows; z++)
{
DataRow item = xlDataset.Tables[0].Rows[z];
Int32 oQtyBon = 0;
var idx = z + 1;
OleDbCommand cmdUpOpening = new OleDbCommand
("UPDATE [Sheet1$E" + idx + ":E" + idx + "] SET F1=" + oQtyBon, objConn);
cmdUpOpening.ExecuteNonQuery();
cmdUpOpening.Dispose();
}
objConn.Close();
objConn.Dispose();
Related
How to add a int to a string Range so that "[A2:B10]" becomes "[A3:B10]"?
RowColRange is in the code a string with a Range.
The code works as expected but i want the first row 2 to 3.
The Input Sheet and RowColRange is defined by user input.
The Problem is E69 starts from E70 in the xls file.
if (Execute)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source = " + PathOpen + ";"
+ "Extended Properties=\"Excel 12.0 Xml;HDR=YES\"");
OleDbCommand com = new OleDbCommand("select * from [" + Sheet + "$" + RowColRange + "]", con);
System.Data.DataSet dSet = new System.Data.DataSet();
OleDbDataAdapter dAd = new OleDbDataAdapter(com);
dAd.Fill(dSet);
DataTree<string> myTree = new DataTree<string>();
int colCount = dSet.Tables[0].Columns.Count;
for (int c = 0; c <= colCount - 1; c++)
{
foreach (DataRow row in dSet.Tables[0].Rows)
myTree.Add(("" + row[c]), new GH_Path(c));
}
Table = myTree;
}
so here is a solution (i am sure not a good one) but i split the string and convert the nessesary part into string and join everything together before it goes to the commandtext.
Regex re = new Regex(#"([a-zA-Z]+)(\d+)([:])([a-zA-Z]+)(\d+)");
Match result = re.Match(RowColRange);
int Num = Int32.Parse(result.Groups[2].Value) - 1;
string newRange = ((result.Groups[1].Value + Num + result.Groups[3].Value + result.Groups[4].Value + result.Groups[5].Value).ToString());
I've been working on this function to take a user selected csv file and parse it into an access database. After much trial and error and reading here, the thing will compile and run without crashing but no values are being inserted into the table. This I where I am at currently.
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
productFileName = productOpenDialog.SafeFileName;
productFilePath = Path.GetDirectoryName(productOpenDialog.FileName);
string connectionString = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source ={0}"+"\\VendorDB.accdb;Persist Security Info = False;", Environment.CurrentDirectory);
string selectSQL = String.Format(#"SELECT * FROM [" + productFileName + "]");
using (OleDbConnection connection = new OleDbConnection(String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Text;", productFilePath)))
{
using (OleDbCommand command = new OleDbCommand(selectSQL, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
//create connection to Access DB
OleDbConnection DBconn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//set cmd settings
cmd.Connection = DBconn;
//cmd.CommandType = CommandType.Text;
//open DB connection
DBconn.Open();
//read each row in the Datatable and insert that record into the DB
for (int i = 0; i < dataTable.Rows.Count; i++)
{
cmd.CommandText = "INSERT INTO Product_List (ProductID, ProductName, Description, InventoryItem, Price, CaseSize, SalespersonID)" +
" VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
"','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
"','" + dataTable.Rows[i].ItemArray.GetValue(6) + "')";
cmd.ExecuteNonQuery();
}
//close DB.connection
DBconn.Close();
}
}
}
}
I am aware that datatypes in fields might be an issue, so I removed a DateTime and changed price to a short number, so all data is strings and numbers. Despite successfully loading the DataTable from the csv file, no values are inserted into access.
I am writing a program to read excel using c# and store in a DataTable. When I check the columns in my DataTable while debugging, I see system columns like Table_Schema, Table_Catalog, Table_Name, Table_Type etc. How do I exclude these unwanted columns?
My code:
string sSheetName = null;
string sConnection = null;
int nOutputRow = 0;
DataTable dtTablesList = default(DataTable);
OleDbCommand oleExcelCommand = default(OleDbCommand);
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFileName.Text + ";" + "Extended Properties=Excel 8.0;";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0].Field<string>("TABLE_NAME");
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName))
{
oleExcelCommand = oleExcelConnection.CreateCommand();
string commandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
OleDbDataAdapter daexcel = new OleDbDataAdapter(commandText, oleExcelConnection);
dtTablesList.Locale = System.Globalization.CultureInfo.CurrentCulture;
daexcel.Fill(dtTablesList);
}
oleExcelConnection.Close();
I am trying to copy an excel sheet with 1 Million records into a Data Table. Unfortunately it takes about 47 seconds to complete this process. Is there a better way to copy this information over in less time?
Here's the code that ports the info in:
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileName +
";Extended Properties='Excel 12.0 XML;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + sheetName + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
dtTemp.Reset();
dtTemp.TableName = userUpload;
sda.Fill(dtTemp); //Puts imported table into the dtTemp table
con.Close();
string fields = "";
string tempString;
foreach (DataColumn col in dtTemp.Columns) //Generates SQL String from imported table
{
tempString = RemoveSpecialCharacters(col.ColumnName);
if (dtTemp.Columns.IndexOf(col) == dtTemp.Columns.Count - 1)
{
fields += " [" + tempString + "] varchar(255)";
}
else
{
fields += " [" + tempString + "] varchar(255)" + ",";
}
}
fields = fields.Trim();
// createSQLConn(fields, connection, connectionTempDB, dtTemp);
}
Given the following code to export each table in the database:
string strSql = "SELECT * FROM " + tableName;
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dbPath);
using (SqliteCommand sqlComm = new SqliteCommand(strSql, sqlCon) { CommandType = CommandType.Text })
{
var da = new SqliteDataAdapter(sqlComm);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Tables[0].WriteXml(Path.Combine(syncPath, tableName + "_4.xml"));
}
I'm trying to import the XML back into the database with the following:
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dataPath + "/Empty.db3");
sqlCon.Open();
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(syncPath, tableName + "_4.xml"));
DataTable dt = ds.Tables[0];
string keyField = dt.Columns[0].ColumnName;
dt.PrimaryKey = new DataColumn[] { dt.Columns[keyField] };
var adapterForTable1 = new SqliteDataAdapter("Select * from " + tableName, sqlCon);
adapterForTable1.AcceptChangesDuringFill = false;
var builderForTable1 = new SqliteCommandBuilder(adapterForTable1);
adapterForTable1.Update(ds, tableName);
sqlCon.Close();
But I get the error: Dynamic SQL generation is not supported with no base table. How do I fix this?
Abandoned the Update option and wrote this:
SqliteConnection sqlCon = new SqliteConnection("Data Source=" + dataPath + "/Empty.db3");
sqlCon.Open();
SqliteCommand sqlCmd = new SqliteCommand(sqlCon);
DataSet ds = new DataSet();
ds.ReadXml(Path.Combine(syncPath, tableName + "_4.xml"), XmlReadMode.ReadSchema);
foreach(DataTable dt in ds.Tables)
{
//Get field names
string sqlString = "INSERT into " + tableName + " (";
string valString = "";
var sqlParams = new string[dt.Rows[0].ItemArray.Count()];
int count = 0;
foreach(DataColumn dc in dt.Columns)
{
sqlString += dc.ColumnName + ", ";
valString += "#" + dc.ColumnName + ", ";
sqlParams[count] = "#" + dc.ColumnName;
count++;
}
valString = valString.Substring(0, valString.Length - 2);
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ") VALUES (" + valString + ")";
sqlCmd.CommandText = sqlString;
foreach(DataRow dr in dt.Rows)
{
for (int i = 0; i < dr.ItemArray.Count(); i++)
{
sqlCmd.Parameters.AddWithValue(sqlParams[i], dr.ItemArray[i] ?? DBNull.Value);
}
sqlCmd.ExecuteNonQuery();
}
}