Updating excel values in data grid view on certain condition - c#

I need to fetch a row value from an excel sheet in data grid view in winform.
I’m able to display the entire excel sheet in the datagridview. But, I need to display particular rows in the grid based on a current date condition.
public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$] WHERE Date=#date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("#date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}
Thanking you in advance

What seems to be happening here is that the Date parameter is not being honored, as you are getting back all of the rows. So, I used Google to figure out how to properly add parameters when using OleDbConnection. I found this:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement
Source: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters
Using the example on that page, try changing your code to this:
string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$] WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
Please note that i've not tested this, so I can't promise it will work. But, the main point is... the answer is out there! You just need to go looking for it.

Related

Reading Excel File using C#

I am new to C# and I am trying to read an excel file with the following code
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath +
";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(conStr))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using (OleDbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
I get the following error:
Sheet1$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
Can anyone tell me whats I am doing wrong?
The name of excel sheet is sheet.xlsx
Thanks
The sheet name might not be the same as the filename, you can get the first sheet name by doing the following
First, get the schema
DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
Then get the first sheets name
var sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
After you get your command, you can then fill a dataset and work with it's .Rows collection
var myDataSet = new DataSet();
command.Fill(myDataSet);
The sheetname is this

in C# using oledb connection string how to Convert Scientific Notation to text strings?

I have a set of data that is downloaded as a Excel file using OLEDB connection string like so:
4552
3.00E+03
3.00E+22
3F45
3.00E+99
DD56677
37
Excel automatically thinks that 3E03, 3E22 and 3E99 are numbers and makes them look like above..
how to get it as a string ?
my code is
DataTable dataTable = new DataTable();
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=" + header + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
OleDbConnection connection = new OleDbConnection(strExcelConn);
using (OleDbCommand command = new OleDbCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.Connection = connection;
//Check if the Sheet Exists
connection.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connection.Close();
connection.Open();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
command.CommandText = "SELECT * From [" + SheetName + "]";
adapter.SelectCommand = command;
adapter.Fill(dataTable);
connection.Close();
}
please can any one help me to get this colum as a string
Have a look at this StackOverflow question entitled How to convert a string containing an exponential number to decimal and back to string.
They use the decimal.Parse(someMoneyVar, NumberStyles.Any) method to do the conversion.
Select Excel Columns by name in your query and cast your required columns to a string using CStr(<columnName>)

Apply a TableStyle to a QueryTable

I can use a query table:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var rng = sheet.Range("A1");
var qt = sheet.QueryTables.Add("ODBC;...", rng, "SELECT * FROM myTable");
qt.Refresh();
and this will import the data correctly (e.g. dates actually display as dates etc...). But when I try and access the ListObject to apply a TableStyle I get an exception.
Now if I add a list object like:
var sheet = (_excel.ActiveSheet as Excel.Worksheet);
var qt = sheet.ListObjects.Add(
Excel.Enums.XlListObjectSourceType.xlSrcQuery,
"ODBC;...",
null,
Excel.Enums.XlYesNoGuess.xlNo,
rng,
"TableStyleMedium9").QueryTable;
qt.CommandType = Excel.Enums.XlCmdType.xlCmdSql;
qt.CommandText = "SELECT * FROM myTable";
qt.Refresh();
The the dates in the query display as decimal numbers and not dates...
I could just format the columns afterwards, but the problem is that I won't actually know the query that is being run as the user types this at runtime, so I would prefer to get Excel to do this.
So essentially, what I want, is to use the first bit of code and apply a TableStyle to it.
Can anyone help?
This doesn't do coloring, but it does organize the data into a datatable, and when you're debugging with breakpoints and mouse over the datatable after its been filled you can see all the data organized into columns. What you can then do with the datatable is bind it to a datagrid view on your win forms element.
I have this DataTable DataTable = new DataTable(); as a global field at the top.
OleDbConnection conn = new OleDbConnection();
//This is making a connection to the excel file, don't worry about this I think you did it differently.
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + stringFileName + ";" + "Extended Properties=\"Excel 12.0;HDR=Yes;\""; OleDbCommand cmd = new OleDbCommand
("SELECT * FROM [" + sheetFromTo + "]", conn);
DataSet dataSet1 = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmd);
try
{
conn.Open();//opens connection
dataSet1.Clear();//empties, incase they refill it later
dataAdapter.SelectCommand = cmd;//calls the cmd up above
dataAdapter.Fill(dataSet1);//fills the dataset
dataGridView1.DataSource = dataSet1.Tables[0];//puts the dataset in the dataGridview
//important** creates a datatable from the dataset, most of our work with the server is with this datatable
DataTable dataTable = dataSet1.Tables[0];
DataTable = dataTable;
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}

Read Excel File Data From OleDbConnection

I'm currently facing a problem whereby I don't know how to fix it.
I upload my precompiled project into IIS. Here is my purpose of this page:
User upload a excel file into a folder in the server. ex #"~/PlanQuantityFile/". It did upload successfully.
Problems faced:
It stops when my scripts trying to open the excel file (for extract data purpose) without showing any errors. At line 881 as shown in the image.
Here is few area I had seek for but it still couldn't solve my problem.
Possible Solution:
connection open but never close, so run out of connection. (but I did close it and the scripts stop running before the close statement)
32 bit program calling 64 bit office. (I had limited knowledge on hardware field, don't know what should I do to troubleshoot here)
permission problem. Need to set the permission of ASP.NET account. (I still finding object names for ASP.NET account)
Thanks for anyone who trying to help. Your advice is invaluable.
OleDbConnection oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
OleDbConnection connExcel = oledbConn;
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of Sheet
try
{
connExcel.Open();// It stops here without showing errors.
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
The following code returns a datatable for selected filelocation source. Remember to rename the sheetname to "Sheet1".
Use Namespace: using System.Data.OleDb;
Function::::
public DataTable GetExcelinDatatable(string filelocation)
{
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("select * from [SHEET1$]", con);
da.Fill(dt);
con.Close();
return dt;
}
you can use mentioned function to read the Excel file you have to just pass the path of excel file
private List<DataTable> readExcel(string strXLS)
{
//DataTable dtExcel = getExcelSheetTable();
List<DataTable> SheetsData = new List<DataTable>();
DataTable dtExcel = new DataTable();
DataTable SocialMediaExcel = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLS + ";Extended Properties=Excel 12.0;";
try
{
OleDbDataAdapter adpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
adpt.Fill(dtExcel);
SheetsData.Add(dtExcel);
}
catch (Exception ex)
{
throw ex;
}
return SheetsData;
}

Attempting to connect to Excel spreadsheet in C#

I am trying to pull a bunch of data from a spreadsheet, however I am not able to make a successful connection in my C# code. B
Below is the connection string and the code that I am using to make the connection. The goal of the program is to pull the data from the spreadsheet and deposit it into a SQL database. I cannot get past the connection.open() command, however without receiveing this error message:
"External table is not in the expected format"
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
counter++;
//Access db values
string compCode = "";
string agId = "";
string fName = "";
string lName = "";
string nameSuffix = "";
compCode = reader.GetValue(0).ToString();
agId = reader.GetString(1);
fName = reader.GetString(2);
lName = reader.GetString(3);
nameSuffix = reader.GetString(4);
sqlComm.Parameters.Add(companyCode);
sqlComm.Parameters.Add(agentID);
sqlComm.Parameters.Add(firstName);
sqlComm.Parameters.Add(lastName);
sqlComm.Parameters.Add(suffix);
//Initialize connection objects
cm = Dts.Connections["QUAHILSQ03"];
sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
//Execute stored procedure
sqlComm.ExecuteNonQuery();
}
reader.Close();
connection.Close();
OleDbConnection.ReleaseObjectPool();
}
For *.xlsx, you need the Ace drivers: Microsoft.ACE.OLEDB.12.0
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
Wrote this a long while back. It's in WebForms, but the .cs file shows you want you need:
converting an excel spreadsheet to a dataset, datatable and multi-dimensional array
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FileToConvert+";Extended Properties=Excel 8.0;";
try
{
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
//this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
adapter.Fill(ds);//now you have your dataset ds now filled with the data and ready for manipulation
// do stuff
}

Categories