"Syntax error in FROM clause" Excel in c# - c#

i have an Excel file i want to raed it in c# using the OleDb like the following code:
string sheetName = "sheet1";
try
{
string stringConnection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=excelfile.xls;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;MAXSCANROWS=0';";
OleDbConnection OleDbConnection_ = new OleDbConnection(stringConnection);
OleDbCommand OleDbCommand_ = new OleDbCommand("select * from [" + sheetName + "$]; ", OleDbConnection_);
OleDbConnection_.Open();
DataTable DataTable_ = new DataTable();
DataTable_.Load(OleDbCommand_.ExecuteReader(), LoadOption.OverwriteChanges);
OleDbConnection_.Close();
}
catch (Exception)
{
throw;
}
Everything is working fine, just when i change the SheetName Value to " topos .architectures. bureaux " like the name in the xls file that i have, an exception was shown:
Syntax error in FROM clause.
what i messed it up here, thank you.

I think you just need to remove the $ in "select * from [" + sheetName + "$]; "
The $ is indeed use in references in Excel itself, but I think is does not apply to the OleDB command syntax
See this question for reference: Reading from excel using oledbcommand

The problem was in the dots in the Sheet name, the dots should be an #.
Like that:
"select * from ['" + sheetName.Replace('.', '#') + "$'];"

Related

Uploading a Excel Sheet in C# using Visual Studio

My code is
string PathConn = "Provider= Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox10.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter dbDataAdapter = new OleDbDataAdapter("Select * From [" + textBox1.Text + "$]", conn);
DataTable dt = new DataTable();
dbDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
I get the error:
System.Data.OleDb.OleDbException: ''$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long
What am I doing wrong?
Could it possibly be the "$"
in
("Select * From [" + textBox1.Text + "$]", conn);
Try
("Select * From "+ textBox1.Text , conn);
or
("Select * From ["+ textBox1.Text +"]", conn);
which looks like a more correct sql statement to me.
And if I might make a suggestion, try giving your text boxes names that mean more so that your code is more maintainable in the future.

C# - OleDBDataAdapter.Fill(DataSet) throws "No value given for one or more required parameters. "

I have the following code to access a .xlsx file and get the sheet named "Sheet1" as a table. Then I select the values for URL and Username using select command.
string strPath = #"C:\Users\...\TestData.xlsx";
string strExcelConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";");
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
try
{
connExcel.Open();
DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmdExcel = new OleDbCommand("SELECT URL, Username From [" + SheetName + "]",connExcel);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT URL, Username From [" + SheetName + "]", strExcelConn);
cmdExcel.CommandText = "SELECT URL, Username From [" + SheetName + "]";
Console.WriteLine(cmdExcel.CommandText);
da.Fill(ds);
connExcel.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
connExcel.Close();
}
Unfortunately, I'm getting the following error during the datafill of the adapter.
da.Fill(ds);
The error says
Message: System.Data.OleDb.OleDbException : No value given for one or more required parameters.
Could someone help me find a solution for this?
The problem was only when I tried to select specific columns. If I have Select * from, it works fine.
But, not sure about the actual issue though.

Read Data from Excel using OLEDB

I read an excel file using OLEDB. Below is the code:
string conn;
conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
("Data Source=" + _filename + ";" +
"Extended Properties=\"Excel 12.0;\""));
OleDbConnection oleDBCon = new OleDbConnection(conn);
oleDBCon.Open();
DataTable dt = oleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SSQL = "SELECT * from [ Sheet1$ ]";
OleDbDataAdapter oleDA = new OleDbDataAdapter(SSQL, conn);
DataSet ds = new DataSet();
oleDA.Fill(ds);
DataTable _DtTable = ds.Tables[0];
oleDBCon.Close();
dataGridView1.DataSource = _DtTable;
foreach (DataRow rows in _DtTable.Rows)
{
string Description = rows[0].ToString();
string Code= rows[1].ToString();
textBox1.AppendText("Printing Description: " + Description + " and Code: " + Code + ",Date:" + DateTime.Now.ToString() + Environment.NewLine);
}
The excel file is as follows:
The data printed in textBox1 are:
Printing Description:Desc 2 and Code: Code 2,Date:20/12/2014 12:36:54 μμ
Printing Description: Desc 3 and Code: Code 3,Date:20/12/2014 12:36:54 μμ
So, my problem is that the 1st row of excel is going to the header of the Datatable. How can I avoid that (without adding any extra 1st row to excel)?
Just add "HDR=No" at the end of your connection string which means "No header row that indicates column but it contains data", then you will be able to fetch 1st row data also.
So your complete connection string would be
conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
("Data Source=" + _filename + ";" +
"Extended Properties=\"Excel 12.0;\";HDR=No"));

How to add column to .DBF file?

One of the issues I have is that, I don't think the table has a name... its just a .dbf file
So I've been trying this:
public void SQLAlter(string dbffile, string ColumnName )
{
//dbffile is "C:\MAPS\WASHINGTON\TLG_ROADS_L.DBF"
//ColumnName is "State"
if (File.Exists(dbffile))
{
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
conn.ConnectionString = #"DSN=dBase Files";
conn.Open();
System.Data.Odbc.OdbcCommand comm = new System.Data.Odbc.OdbcCommand();
comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
comm.ExecuteNonQuery();
}
}
The error is :
base {System.Data.Common.DbException} = {"ERROR [42S02]
[Microsoft][ODBC dBASE Driver] Cannot find table or constraint."}
I believe the table name is supposed to be the filename, and the connection string should point to the folder containing the dbf file.
var path = Path.GetDirectoryName(dbffile);
var tableName = Path.GetFileName(dbffile);
// ...
conn.ConnectionSTring = #"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=" + path;
comm.CommandText = "ALTER TABLE " + tableName + //...
Check connectionstrings.com: http://connectionstrings.com/dbf-foxpro
This is actually the correct syntax
comm.CommandText = "ALTER TABLE " + dbffile + " ADD COLUMN " + ColumnName + " VARCHAR(1024)";
However if your filename is longer than 8 characters it will not find it. Even though I tried it will an appropriate length file name, the "Operation [is] not supported on a table that contains data."
Various Internet links seem to indicate that one has to create a new table, and copy all the fields over.
Try another Provider.
It worked for me with the Visual Foxpro Provider
conn.ConnectionString = #"Provider=VFPOLEDB.1; Data Source=Themes.dbf" + #"\;Extended Properties=dBase IV";
If the driver is not installed on your machine, you get it here :
http://www.microsoft.com/en-us/download/details.aspx?id=14839

How to count empty rows when reading from Excel

I'm using OLEDB to connect and read through data from an Excel spreadsheet. I have IMEX="1" and everything works ok. My problem is the sheets I'm reading from may start with several empty rows and the number of empty rows is important. For example, if I was reading a 5x5 grid like:
- - - - -
- - - - -
2 - 3 3 8
- - - - -
- - 5 2 2
where '-' represents an empty cell. The fact that the first two rows are empty is important. The size of the grid is dynamic. My code appears to be ignoring the first empty rows. But deals with the empty row at line 4 ok.
How can I count the number of empty rows at the start of an Excel sheet using OLEDB?
I'm restricted to using OLEDB, I wouldn't if I didn't have to ;-)
using (var adapter = new OleDbDataAdapter("SELECT * FROM [" + worksheetName + "]", connString)) {
var ds = new DataSet();
adapter.Fill(ds, "FareChart");
table = ds.Tables["FareChart"];
}
Connection string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Windows\\TEMP\\e1842f90-74a7-42f2-a6fa-208396a1072e;Extended Properties=\"Excel 8.0;IMEX=1;HDR=No\""
UPDATE
Specifying '.xls' as the file extension in the connection string fixed this issue and correctly reads the empty rows at the start.
I think your problem is with your connection string. I tested the below code and it worked for me:
DataSet Contents = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter("select FirstName,LastName,Email,Mobile from [" + mySheet + "]", connection))
{
adapter.Fill(Contents,"MyTable");
}
foreach (DataRow content in Contents.Tables["MyTable"].Rows)
{
if (content[0].ToString() == "" && content[0].ToString() == "" && content[0].ToString() == "" && content[0].ToString() == "")
{
Console.WriteLine("Empty Row");
}
else
{
Console.WriteLine(content[0] + " | " + content[1] + " | " + content[2] + " | " + content[3]);
}
}
My Connection String is:
string cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Untitled 1.xls\";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
check below code :It will return the empty rows..
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 8.0;HDR=NO;IMEX=1\";"); /*for office 2007 connection*/
conn.Open();
string strQuery = "SELECT * FROM [" + Table + "]";
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);
System.Data.DataTable ExcelToDataTable = new System.Data.DataTable();
adapter.Fill(ExcelToDataTable);
DT = ExcelToDataTable.Copy();
int count = DT.Rows.Cast<DataRow>().Where(row => row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).ToList().Count();
As stated by #Knvn
You need to specifiy the file extension .xls with the file name in your connection string.

Categories

Resources