oledb Syntax error (missing operator) in query expression - c#

I'm trying to import xlsx to datagrid using oledb.
but I'm getting this: Syntax error (missing operator) in query expression.I've read other related posts but didn't helped
this is the code:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\alm1.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbCommand command = new OleDbCommand("SELECT TXT" + "FROM [2$]", conn);
DataSet dstxt = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(dstxt);
dataGridView1.DataSource = dstxt.Tables[0];
can anyone help? I'm pretty sure it's a stupid mistake of me but can't figure it out.

Related

importing excel data to database using asp.net and c #

am getting the following error while trying to import data from excel to the database.
The Microsoft Office Access database engine could not find the object
'C:\Users\DAKTARI\Desktop\smarttable.xls'
this is my code behind that am using.
public partial class Smarttable : System.Web.UI.Page
{
OleDbConnection Econ;
SqlConnection con;
string constr, Query, sqlconn;
protected void Page_Load(object sender, EventArgs e)
{
}
private void ExcelConn(string FilePath)
{
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;""");
Econ = new OleDbConnection(constr);
}
private void connection()
{
sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
con = new SqlConnection(sqlconn);
}
private void InsertExcelRecords(string FilePath)
{
ExcelConn(FilePath);
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
OleDbCommand Ecom = new OleDbCommand(Query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable Exceldt = ds.Tables[0];
connection();
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
//assigning Destination table name
objbulk.DestinationTableName = "smarttable";
//Mapping Table column
objbulk.ColumnMappings.Add("InvoiceNumber", "InvoiceNumber");
objbulk.ColumnMappings.Add("AmountPaid", "AmountPaid");
objbulk.ColumnMappings.Add("Remarks", "Remarks");
//inserting Datatable Records to DataBase
con.Open();
objbulk.WriteToServer(Exceldt);
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
InsertExcelRecords(CurrentFilePath);
}
}
Your Excel file format uses XLS which means for Office 2003 or earlier, but you're using ACE OLEDB provider which used for Office 2007 or later:
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;"");
The correct usage is using Jet 4.0 provider like this:
constr = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'", FilePath);
Also you have second issue which a wrong query string is used to read the data inside worksheet:
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
This should be changed to proper form below:
Query = "SELECT [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
Change this line
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
To
Query = "Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
The FROM needs to be followed by the Sheet Name which is treated like a table

Trouble including a string in an SQL query for an Excel Spreadsheet

I am displaying data from an Excel Spreadsheet through an ASP.net web form using C#. I would like to run an SQL query on the data, but am having trouble figuring out how to use a string in my query.
Here is the code I am running in my .aspx.cs file. I am also using a .aspx to display the data in a GridView.
protected void Page_Load(object sender, EventArgs e)
{
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("ExcelCSTest.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
string sSQL = "SELECT * FROM [Sheet1$A1:D14]";
OleDbCommand objCmdSelect = new OleDbCommand(sSQL, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1, "XLData");
GridView1.DataSource = objDataset1.Tables[0].DefaultView;
GridView1.DataBind();
objConn.Close();
}
Ideally, I would like to add a WHERE clause to my string sSQL = "SELECT * FROM [Sheet1$A1:D14]"; in order to query the current month and display the row of said month from the Excel Spreadsheet.
I have rewritten your code for you, however, you should seriously consider sticking into some coding standards. Please don't end your variables with numbers and consider formatting your code then it's more readable. Also you need to surround your OleDbConnection() inside a using statement then it gets disposed properly.
Here is the formatted and reworked code
public partial class ExcelAdapter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("ExcelCSTest.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
using (OleDbConnection objConn = new OleDbConnection(sConnectionString))
{
objConn.Open();
var sSQL = "SELECT * FROM [Sheet1$A1:D14]";
OleDbCommand objCmdSelect = new OleDbCommand(sSQL, objConn);
objCmdSelect.CommandType = CommandType.Text;
DataSet objDataset = new DataSet();
OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmdSelect).Fill(objDataset);
objConn.Close();
}
}
}
I haven't had time to test this code but I am pretty sure it should be spot on. (I hope)
Further more have a look at this tutorial. It's an excellent source to give you an idea of how to do this job properly.
Import Excel File to DataSet
Where Clause
It's very easy to add the where clause to your SQL and even better you can parametrize it to make it more standard.
Your code should look something like
var sSQL = "SELECT * FROM [Sheet1$A1:D14] WHERE currentDate = ?";
cmd.Parameter.Add("#Param1", OleDbType.VarChar).Value = todaysDate;
For the full example of how the parametrization should be done have a look at OleDbCommand.Parameters Property and also for even more details on an example you can check my answer's example to this question Missing Required Parameter in Parameterized Query?

Querying an Excel File from C# - No Results

I have been attempting to query an excel file from C# using an OLEDB connection. There are no runtime errors when the program runs, but it returns no results. I have tried it with different excel files but have gotten a similar result.
edit: The excel file is located in the project directory. If I remove the excel file from the current location the program will get a file not found exception.
private void btnRun_Click(object sender, EventArgs e)
{
string strFileName = "playerData.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties=" + "\"Excel 8.0;HDR=YES\"";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dgsResults.DataSource = ds;
conn.Close();
}
Does anyone know why this returns no results?
Thanks,
You are using strFileName in the connStr yet you have not provided the path with it.
Should be along the lines of:
string strFileName = #"c:\excel location\playerData.xls";
Apparently the specific data table has to be referenced in the data binding process. Adding the following line after the fill() method has solved the issue.
da.Fill(ds);
dgsResults.DataSource = ds.Tables[0]; //this is the line to be added

SQLException was Unhandled. Viewing Excel File in GridView

I've been doing a C# project where I browse and view an Excel File into a gridview. However, there is an error message which I don't understand. Can someone please help me out on this.
This is the code I used:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
This is the error message:
"A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections.
(provider: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)."
You are trying to connect to Excel via a SqlConnection.
To connect to Excel use OleDBConnection:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text)
var objConn = new OleDbConnection(connectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1);
objConn.Close();
}
You can not use SqlConnection or SqlDataAdapter for ODBC or JET connections. Use OleDbConnection or OleDbDataAdapter.
Please also make sure to dispose of connections and resources in a timely manner. Using the using statement is recommended here.
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
DataSet objDataset1 = new DataSet();
using (OleDbConnection objConn = new OleDbConnection(connectionString))
{
objConn.Open();
using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn))
using (OleDbDataAdapter objAdapter1 = new OleDbDataAdapter())
{
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1);
}
}
}

How to select specific cells (from different rows or columns) from an excel file using VS 2010, C#, oledbconnection

This is the code i'm using in my project:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\KursniListi.xlsx" + #";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbCommand command = new OleDbCommand
(
"SELECT *" +
"FROM [Sheet1$]", conn
);
DataSet dsKL = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(dsKL);
dataGridView1.DataSource = dsKL.Tables[0];
}
http://uploadpic.org/v.php?img=j8nn3BtVP2
I need this to display me: rows 1 and 11, columns C,E,F
You can hide columns and rows on your datagrid using the Visible property
this.dataGridView1.Columns[0].Visible = false;
....
this.dataGridView1.Rows[1].Visible = false;
....
(I have used the index for the columns/rows because I can't type your header names)
However without knowing the requirement to hide rows it's difficult to give a satisfying answer.

Categories

Resources