I have connection string with IMEX option (all types are converted to string):
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"{0}\";Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\";", strFile);
I use followed code to read xslx file into DataTable
DataTable table = new DataTable(name);
string sql = "SELECT * FROM [" + name + "]";
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(table);
Program reads the same file on two computers.
When the program runs on the first computer, I get date like string "31.03.2021". When the program runs on the second computer, I get the date like string "3/31/2021".
I cannot get the same date format on both computers. I already tried to:
Change the language format in Windows settings.
Set
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Set
table.Locale = new CultureInfo("en-US");
Nothing helps
I couldn't find any Solution. So I started to use a option IMEX=0 instead of IMEX=1.
Date are read correctly as DateTime type.
Related
I am trying to access to an old DBase file with Ado.Net C#. I successfully opened file but some string records in table has TAB character like "Some text/TABOther text". Ado.Net driver successfully reads "Some text" and can not read rest of the data. Is there are a way to let Ado.Net read all the content of the cell?
My connection string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DATA DIRECTORY;Extended Properties=dBASE IV;User ID=;Password=;";
Select query:
var sql = "select * from " + "MY_TABLE";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
I would use VFPOLEDB driver from Microsoft.Jet driver is good for maybe dBase II but not trustable for the later versions (like dBase IV).
DataTable tbl = new DataTable();
new OleDbAdapter("select * from MY_TABLE",
"Provider=VFPOLEDB;Data Source=DATA DIRECTORY",
).Fill(tbl);
And be sure you only have TAB character in between. While xbase databases can store any character in a string field, in C# (contrary to documentation) strings are ASCIIZ strings like in C. Also if that string has NEWLINE character in it, in DataTable you might not see that.
PS: Try posting to Visual-Foxpro tag next time. That one has more interest.
My problem specifically is I can't filter by a Date field.
Here is my code:
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\Tools;Extended Properties=dBASE IV;User ID=Admin;Password=;";
using (OleDbConnection con = new OleDbConnection(connstr))
{
string sql = "select USERNUMBER,FIRSTNAME,LASTNAME, LASTACCESS from EMP WHERE TERMINATED=\"Y\" AND [LASTACCESS]<\"2001/10/20\"";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
It works fine if I omit the date field. I just can't figure out what the format is. If I look at the table with a dbf viewer utility the LASTACCESS field is in dd.mm.yyyy (with the periods as separators, but I don't know if that is just a behavior of the utility).
If I omit the forward slashes from the date field, it works but returns zero records (even though I know there are).
Try this and forget date time hell
string sql = "select USERNUMBER,FIRSTNAME,LASTNAME, LASTACCESS from EMP WHERE TERMINATED=\"Y\" AND [LASTACCESS]<#StartDate";
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.AddWithValue("#StartDate", new DateTime(2001, 10, 20));
Just use parameters and forget about formatting them yourself .
The framework is here to help you and provide solutions already tested and working like a charm
Simply I have an Excel file and I loaded it into SQL Server 2008.
I want to insert current date into the same cells added from Excel while date transferring... then date inserted automatically every time I added data and never lose old date. How can I do this?
string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
string myexceldataquery = "select * from [" + ssqltable + "$]";
try
{
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + imagepath + ";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
oconn.Open();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
bulkcopy.DestinationTableName = ssqltable;
for (int i = 0; i < dt.Columns.Count; i++)
{
bulkcopy.ColumnMappings.Add(i, i);
}
bulkcopy.WriteToServer(dt);
oconn.Close();
}
I used this but I know insert for only last record
I want to insert current date in newly created rows and doesn't lose previous columns date .. for example when i insert data each time insert new date saving old data with old date
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values('" + DateTime.Now.ToShortDateString() + "')", conn);
Update6.ExecuteScalar();
while using
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteNonQuery();
the result was
enter image description here
So what's the solution ?
Set GETDATE() as the default constraint for your Date column of Overseas table.
SQL Command to add constraint:
ALTER TABLE Overseas
ALTER COLUMN Date DATETIME NOT NULL DEFAULT GETDATE()
Post this, you need not pass any value to this column while inserting. Just insert the remaining columns, this will get inserted automatically.
OR
Try this:
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteScalar();
Based on your DB screenshot hope this query helps:
INSERT INTO Overseas (EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,Date,ID)
SELECT EnglishName,ProductCode,ProductName,TerritoryCode,TerritoryName,Salesvalue,CreditValue,NetSalesValue,Sales,Bonus,Bioxellbricks,BioxellTerritories,GETDATE(),ID from [exceltablename]
Here Overseas is your DB table and exceltablename is your source table of excel.
You can simply use Datetime.Now(); function to get current date.
Also Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
Custom Date and Time Format Strings
Hope this will works for you .. Thank you
There is a function GETDATE() for this purpose.
Returns the current database system timestamp as a datetime value
without the database time zone offset. This value is derived from the
operating system of the computer on which the instance of SQL Server
is running.
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
I'm using oledb to read from excel file.
DataTable sheet1 = new DataTable();
string excelCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
using (OleDbConnection connection = new OleDbConnection(excelCS))
{
connection.Open();
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
adapter.Fill(sheet1);
}
connection.Close();
}
But there is a problem with some cells of the file.
For some cells I get an empty value instead of text. I tried to put some other text into these cells but it didn't work - I'm still getting empty strings.
But after deleting the column and inserting again my application get the right value of cell. Important is that the problem is not with all cells in the column.
Is this a problem with cell format or something? This excel file will be generated by another system so I won't be able to modify it manually.
Has anybody any sugestions what's wrong and what can I do?
Use IMEX = 1 at the end of your connection string. That will fix your problem.
To always use IMEX=1 is a safer way to retrieve data for mixed data
columns. .."
Remember that, sometimes there are some errors involved using IMEX while you're using Update rather than Selecting.
using this method convert Execel to Dataset without Empty String in c#
public static DataSet ConvertExcelToDataTable(string FileName)
{
DataSet ds = new DataSet();
string strConn = "";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FileName + ";Extended Properties=\"Excel 8.0; HDR=YES; IMEX=1;\"";
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
da.Fill(ds);
return ds;
}
it will return dataset.
I had this issue. What I found was that on the cells that returned blank values the data looked like strings, but the rest of the data looked like numbers, so excel stored the strings in a different place as the numbers. I changed the column format to text and all the data was picked up.
This thread might help with changing the format: Format an Excel column (or cell) as Text in C#?
I have been trying to read data from an excel file. It has been successful, but I enountered a problem. Whenever the format of the cell and the data entered in the cell is not matching then I get empty data
e.g
If the data cell is formatted as Date - dd/mm/yyyy, and the user enters 13/17/2011, the as the date format and the date entered is contradictory so the excel gives me entirely empty cell. Only if the cell format is text I get the data as entered.
Why is the excel file giving me empty cell in case the entered date format is not complying with the cell format set?
This is the code that reads the excel data
if(fileEXT.Equals(".xls"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 8.0");
}
else if(fileEXT.Equals(".xlsx"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=\"Excel 12.0;HDR=YES;\"");
}
else if(fileEXT.Equals(".xlsm"))
{
oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 12.0 Macro");
}
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds,"LocationDetails");
You can change your connection string to
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath("../Portal_Docs/UploadDocs/"+filename+"")+";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1"
HDR=Yes;IMEX=1
tells OldDb driver that data at columns in defferent format.
Instead of OLEDB, I would suggest using EPPLus library to handle your excel files.It is very easy and comprehensive. Nuget package is also available for the same. http://nuget.org/packages/EPPlus