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());
Related
I have an Excel spreadsheet that I receive that I need to import into a table in our database. I have previously asked about pulling a single cell of data from a spreadsheet (Read a single cell from Excel to a string using C# and ASP.NET) and I am attempting to build off of this in order to move an entire spreadsheet into the database.
The format of the information is Column 1 = Name, Column 2 = Wage, Column 3 = Department
The existing code is as follows:
#region Initialize Connection
var Class_Connection = new SQL_Connection();
var sql = new SQL_Statements();
Class_Connection.cnn.Close();
#endregion
string properties = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\Hera\Public\LumberPrices\lbr_ems.xls; Extended Properties = 'Excel 8.0; HDR = NO;'");
string Price = "";
using (OleDbConnection conn = new OleDbConnection(properties))
{
string sqlpull = "SELECT * FROM [" + worksheet + "$" + Cell1 + ":" + Cell2 + "]";
conn.Open();
DataSet ds = new DataSet();
//string columns = String.Join(",", columnNames.ToArray());
using (OleDbDataAdapter da = new OleDbDataAdapter(sqlpull, properties))
{
string temp2 = "";
var dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
temp2 = dt.Columns[i].ColumnName.ToString();
}
foreach (DataRow dr in dt.Rows)
{
Price = dr[temp2].ToString();
}
}
}
int Freight = GetFreight(LumbDesc);
int price1 = Convert.ToInt32(Price);
int addon = Convert.ToInt32(AddTo);
int Total = price1 + addon + Freight;
//TODO: insert into TLumberprice
string sqlStatement = "insert table([LumberCode], [Price], [PriceDate], [UserName], [Factor], [Op])" +
"values ('" + LumbDesc + "', '" + Total + "', '" + DateTime.Now + "', '" + LoginSession.userName.Remove(LoginSession.userName.Length - 1) + "', '" + Factor + "', '" + OP + "')";
#region Insert Lumber Prices
Class_Connection.cnn.Open();
SqlCommand InsertLumberPrices = new SqlCommand(sqlStatement, Class_Connection.cnn);
InsertLumberPrices.ExecuteNonQuery();
Class_Connection.cnn.Close();
#endregion
This works as intended. but I have questions.
Can I read the DataTable(dt) straight into the database, or do I have to use something like the following?
for (int i = 0; i < dt.Columns.Count; i++)
{
SName = dt.Columns[0].ColumnName.ToString();
SWage = dt.Columns[1].ColumnName.ToString();
SDept = dt.Columns[2].ColumnName.ToString();
}
foreach (DataRow dr in dt.Rows)
{
Name = dr[SName].tostring();
Wage = dr[SWage].tostring();
Dept = dr[SDept].tostring();
}
There is a way of importing the data from a data table into the SQL Table.
You need to use SqlBulkCopy
var sqlBulkCopy = new SqlBulkCopy(conn);
You can even map which data table column goes to which SQL Table column as well.
Here is an example.
using(var sqlBulkCopy = new SqlBulkCopy(conn))
{
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 1", "Name"));
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 2", "Wage"));
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 3", "Department"));
sqlBulkCopy.DestinationTableName = "table" // table name in SQL
conn.Open();
sqlBulkCopy.WriteToServer(dt);
conn.Close();
}
Where conn is your SqlConnection.
If you don't want to use the data table, you could go directly to the BulkImport.
Just change the OleDbDataAdapter to OleDbCommand and put the value in an IDataReader variable, which then you can use in the code above instead of dt.
With the last part, I only did it in the past between 2 SQL servers that did not have a link to each other. I'm not sure 100% sure if it will work with OleDb.
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();
I am trying to count the number of values on a column that are before a certain date. The below is my current attempt. I am able to run this no problem without the where section, however of course this is needed for the correct value to be returned.
string type = "Beacon Comm" this is the sheet name.
TargetBuildOledbConnection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + FTPYTracker + "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"
string AssyColumn = "F" or whichever colum to search
DateTimeSelection = "03/01/2020 00:00:00" or data from a date picker in the same format.
public double GetInProgressOledb(string type, OleDbConnection FTPYBuildOleDbConnection, string AssyColumn, DateTime Selection)
{
const string prodParamName = "#prod";
double lastDayOfMonth = (new DateTime(Selection.Year, Selection.Month, 1).AddMonths(1).AddDays(-1)).ToOADate();
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = FTPYBuildOleDbConnection;
comm.CommandText = string.Format(ci, "SELECT Count(*) FROM [" + type + "$" + AssyColumn + ":" + AssyColumn + "] WHERE [" + AssyColumn + "$] = #" + lastDayOfMonth + "#");
//comm.Parameters.Add(prodParamName, OleDbType.VarChar);
//comm.Parameters[prodParamName].Value = lastDayOfMonth;
double rowCount = Convert.ToDouble((int)comm.ExecuteScalar());
return rowCount;
}
}
Try this
comm.Parameters.Add("#prod", OleDbType.VarChar).Value = lastDayOfMonth;
I am working on a c# project and in this project, I want to select some data and show in a datagridview but I have data in my database and I have a query of select but when I click the button so I get this type of error this no row at position 0
Here are the screenshots
https://imgur.com/PKvcgY9
https://imgur.com/aeq0weF
https://imgur.com/8AG3LZ4
Here is my code
dataGridView4.Columns.Add("", "Leave Consumed");
dataGridView4.Columns.Add("", "Leave Allaowed");
dataGridView4.Columns.Add("", "Balance");
for (int i = 0; i < dataGridView4.Rows.Count; i++)
{
DataSet ds1211122 = new DataSet();
DataTable dt1211122 = new DataTable();
ds1211122.Tables.Add(dt1211122);
OleDbDataAdapter da1211122 = new OleDbDataAdapter();
da1211122 = new OleDbDataAdapter("SELECT Sum(USERID) FROM [CHECKINOUT] where " +
"[CHECKTYPE]= '" + "I" + "'AND [USERID] = " +
dataGridView4.Rows[0].Cells[1].Value.ToString() + "AND [CHECKTIME] Between #" +
dateTimePicker2.Value.ToString() + "# AND #" +
dateTimePicker1.Value.ToString() + "# Group By [USERID];", VCON);
da1211122.Fill(dt1211122);
int num = 0;
num = Convert.ToInt32(dt1211122.Rows[0][0].ToString());
VCON.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);
}