Can't open csv file using OleDB - c#

I am new in this so i cant find the solution for my problem.I want to read .csv file in DataTable using OleDB.Here is my code
string file = "D:\\MyFile.csv";
string dir = Path.GetDirectoryName(file);
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
DataTable dt = new DataTable();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + file + "]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(dt);
objConn.Close();
But I am getting an error: The Microsoft Jet database engine could not find the object 'D:\MyFile.csv'. Make sure the object exists and that you spell its name and the path name correctly.
The file is on the right place, so can you tell me what could be the problem?

Place the file inside some folder in D:\ and then retry
GetDirectoryName functions usually returns '' when using such like
GetDirectoryName('C:\asd.txt') returns '' so use it like
GetDirectoryName('C:\myfol\asd.txt') it will returns 'C:\myfol'
and your code is concatinating directory name so chances are you are concatinating a blank string ''
in the line
1. String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";
2. sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0.; Data Source = ''; // as dir is ''
check
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
for additional help.

You need to remove the path from the file name in this line:
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + file + "]", objConn);
It should read:
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + Path.GetFileName(file) + "]", objConn);
In the connection string you're telling the engine the directory, in the command you're telling the engine the file to use (the path could be seen as the equivalent of a database, the file as the equivalent of a table).
You could improve this as follows:
string file = "D:\\MyFile.csv";
string dir = Path.GetDirectoryName(file);
string name = Path.GetFileName(file);
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties='text;HDR=Yes;FMT=Delimited'";
...
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + name + "]", objConn);
...

Try with actual filename in select query.
SELECT * FROM [MyFile.csv]
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [MyFile.csv]", objConn);

Related

Select specific row in SQL Server

I´m starting to develop in C# and SQL Server, I don´t know how to extract information from one excel specific colum.
I have this code working, but what i need it´s to compare a textbox with a specific column and get the data:
Example
Select *
From T_Empleado
Where "Specific column" = "textbox".
public void mostrarExcel()
{
String name = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + "C:\\Users\\alegriad\\Desktop\\sample\\Book2.xlsx" + "; Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]'", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgv_Reporte.DataSource = data;
}//mostrarExcel
Thank you.
You can write your query like this
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where columnName = '"+ YourTextboxValue+ "'" , con);
I try with sample excel like below
And my query like this
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] WHERE Name = 'T1'", con);
This works for me.

.Dat file to dataset

I have a .dat file that I need to import into a datatable. I am using .net framework 4.5 and it delimited by ~. How do I import this? I tried
string mySelectQuery = "SELECT * FROM " + fileName;
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + fileLocation + ";Extended Properties=\"text;HDR=YES;FMT=Delimited\"");
OleDbDataAdapter dsCmd = new OleDbDataAdapter(mySelectQuery, myConnection);
//Fill the DataSet object
dsCmd.Fill(myData, "Packets");
Please help

Import data from excel into DataGridview with specific condition

This is how i am import my Excel file:
stirng file = "c:\myFile.xlsx";
DataGridView dgvIM;
private void Import()
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
file +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
What i want to do is import my Excel file but with specific condition, my second column contain several groups of strings ("First", "Second" etc..) and i want to add only the column with name "First" and not the whole list.
How can i do that ?
Just use a where condition on the sql command like this
string cmdText = "Select * From [" + name + "$] WHERE secondColumnName = 'First'";
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand oconn = new OleDbCommand(cmdText con))
{
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
Note that in your connectionstring you specify HDR=YES, this means that the first non blank line of your excel sheet contains headers that are interpreted as column names. You should update your query setting the correct column name in the WHERE condition
EDIT In response at your comments below, if you want to retrieve every row where AGE is 12 the query becomes
string cmdText = "Select * From [" + name + "$] WHERE Age = 12";

Missing rows reading generated Excel file

I am creating an Excel File using OleDB, it works perfectly, next, I add rows to the file using directly in Office Excel , after, when i try read the file using OleDB again, the rows i added manually does not appear, only the columns and rows i wrote when i created the file.
Here is the code:
//Creation of the file
String connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Mode=ReadWrite; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=0'";
OleDbConnection oledbconnection;
oledbconnection = new OleDbConnection(connectionString);
oledbconnection.Open();
String query = "CREATE TABLE [Sheet1] (....) ";
OleDbCommand cmd = new OleDbCommand(query, oledbconnection);
cmd.ExecuteNonQuery();
oledbconnection.Close();
it works perfectly, the file is created correctly, then, when im trying read the file after modify it, I'm doing this
String connectionStringRead = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + path + "; Extended Properties= 'Excel 8.0; HDR=Yes; IMEX=1'";
OleDbConnection oledbconnection;
oledbconnection = new OleDbConnection(connectionStringRead);
oledbconnection.Open();
DataTable table = new DataTable();
String sheetName;
sheetName = oledbconnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", oledbconnection);
adapter.Fill(table);
oledbconnection.Close();
return table;
The table contains ONLY the original information, not the rows I added using MS Excel.
I don't understand this, can you help me please ?
thanks in advance
Never try like that before, but if
sheetName = "Sheet1" '-------> or whatever
It should be
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "$]", oledbconnection);

data import from excel facing an issue

I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>

Categories