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.
Related
UPDATE:
I have found that this code works! it searches the Excel sheet and only outputs the data I need.
But can anyone explain to me why this works? how does it know that the first line in the spreadsheet is the "index"??
//Coneection String by default empty
string ConStr = "";
//connection string for that file which extantion is .xlsx
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\TestExcel.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
//making query
string query = "SELECT * FROM [lol$] where ID='i2200'";
//Providing connection
OleDbConnection conn = new OleDbConnection(ConStr);
//checking that connection state is closed or not if closed the
//open the connection
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
//create command object
OleDbCommand cmd = new OleDbCommand(query, conn);
// create a data adapter and get the data into dataadapter
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the Excel data to data set
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
lblud.Text = "" + row["Hylde"];
}
OLD
I have been trying to do this for several hours now but no matter what i try, I don't end up with the result i want.
So now im "starting from scratch" again. See if I have approached this incorretly.
Question:
I wan't to create a ASPX website that can search my excel sheet for specific data.
Something like Select * from [Sheet1$] where Column A = i2200
then display only Column B and C from that specific row into a Label / two labels.
See picture here: http://itguruen.dk/EXCEL.png
Does anyone have a simple way of doing this?
Thanks in advance!
Jasper
Have you thought about importing the Excel Spreadsheet into a DataTable, and then analyse that DataTable to populate your labels? You can perform SQL queries on DataTables, so you'll be able to extract the exact data you require quite easily (the hardest part will be importing the Excel Spreadsheet into the DataTable).
There's a very detailed report on this process here: http://www.aspsnippets.com/Articles/Read-and-Import-Excel-File-into-DataSet-or-DataTable-using-C-and-VBNet-in-ASPNet.aspx
Update the post so you can see the solution.
Allthough I dont really know why this works??
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 want to write RightOuterJoin query to retrieve data from access database.. How can i implement this query in c#?
I tried Like this
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=Sample1.accdb; Jet OLEDB:Engine Type=5";
string sql = "SELECT t1.mobileno,t1.RetailerNo,t1.custcode,t2.RET NO FROM [C:\\Sample1.accdb].[Table1] as t1 RIGHT OUTER JOIN [C:\\Sample1.accdb].[Table2] as t2 ON t1.RetailerNo = t2.RET NO";
database = new OleDbConnection(connectionString);
database.Open();
OleDbCommand cmd1 = new OleDbCommand(sql, database);
OleDbDataAdapter da = new OleDbDataAdapter(cmd1);
//database.Open();
//conn.Open();
cmd1.ExecuteNonQuery();
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
I think you may have a problem with your connection string. It uses the Jet provider, but the database type is the newer ACCDB format. Jet does not work with ACCDB.
For ACCDB, you need the ACE provider. If you don't have Office 2007 or 2010 installed, you can download and install the Access Database Engine Redistributable.
Here is the provider section from a working connection string:
Provider=Microsoft.ACE.OLEDB.12.0
See Connection strings for Access 2007 for more details.
Once you have a working connection to Sample1.accdb, revise your SQL statement to this:
SELECT t1.mobileno,t1.RetailerNo,t1.custcode,t2.[RET NO]
FROM
Table1 as t1
RIGHT JOIN Table2 as t2
ON t1.RetailerNo = t2.[RET NO]
Notes:
Since you're already connected to Sample1.accdb, you don't need to prefix the table names with the path to the db file.
For a field name which includes a space (RET NO), enclose the field name in square brackets.
Try the following code
select * from tblemp right join tblDept on tblemp.DeptId=tblDept.pkDeptId
Its is the same as you use right join in SQL SERVER.
I'm new to c#.net
I have excel sheet and I want to import into database.
I want to read it cell by cell and want to insert value in database.
this.openFileDialog1.FileName = "*.xls";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
string path = openFileDialog1.FileName;
string connectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=no;IMEX=1;""", openFileDialog1.FileName);
string query = String.Format("select * from [{0}$]", "Sheet3");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
I assume that after you execute the code in your question, you can see the values within dataGridView1.
The actual reading from the excel sheet is done when calling dataAdapter.Fill. So, in your case, reading the cells comes down to indexing columns and rows in dataSet.Tables[0].
For example:
for (int row = 0; row < dataSet.Tables[0].Rows.Count; row++)
{
DataRow r = dataSet.Tables[0].Rows[row];
}
Accessing the cells in row r is trivial (like the sample above, just for cell).
EDIT
I forgot to describe the "insert the values into a database" part. I presume that the database is SQL Server (may be Express edition, too).
First: create a database connection. Instead of manually composing the connection string, use the SqlConnectionStringBuilder:
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.DataSource = <your server instance, e.g. "localhost\sqlexpress">;
csb.InitialCatalog = <name of your database>;
csb.IntegratedSecurity = <true if you use integrated security, false otherwise>;
if (!csb.IntegratedSecurity)
{
csb.UserId = <User name>;
csb.Password = <Password>;
}
Then, create and open a new SqlConnection with the connection string:
using (SqlConnection conn = new SqlConnection(csb.ConnectionString))
{
conn.Open();
Iterate over all the values you want to insert and execute a respective insert command:
for (...)
{
SqlCommand cmd = new SqlCommand("INSERT INTO ... VALUES (#param1, ..., #paramn)", conn);
cmd.Parameters.AddWithValue("#param1", value1);
...
cmd.Parameters.AddWithValue("#paramn", valuen);
cmd.ExecuteNonQuery();
}
This closes the connection, as the using block ends:
}
And there you go. Alternatively, you could use a data adapter with a special insert-command. Then, inserting the values would come down to a one-liner, however, your database table must have the same structure as the Excel-sheet (respectively: as the data table you obtained in the code you posted.
Check out NPOI
http://npoi.codeplex.com/
It's the .NET version of Apache's POI Excel implementation. It'll easily do what you need it to do, and will help avoid some of the problems ( i.e. local copy of Excel, or worse, copy of Excel on the server ) that you'll face when using the Jet provider.
currently I am having sucsess with reading the excel file with my c# ,net 2 winform application. All works well with string and numerical types, but when it comes to date columns it still casts them as string.
I have read that ado.net scans the first eight rows and then uses that to determine the datatype...I have extended my test file to include more than eight rows - but I still have the same results.
thanks for any help you can provide
DataTable tbl = new DataTable();
OleDbConnection dbConnection =
new OleDbConnection (#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;HDR=Yes;""");
dbConnection.Open();
try
{
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", dbConnection);
dbAdapter.Fill(tbl);
}
finally
{
dbConnection.Close();
}
.net 2.0, c#, vs2008
Is the field formatted as date in the excel file?