Syntax error when opening an Excel workbook using C# - c#

When I try to open an Excel workbook I get a syntax error. Here is the code I'm using:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + fileName + ";"
+"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";
OleDbConnection objConn = new OleDbConnection(connectionString);
OleDbCommand objCommand = new OleDbCommand(#"SELECT * FROM Sheet1$", objConn);
OleDbDataAdapter odjAdp = new OleDbDataAdapter();
odjAdp.SelectCommand = objCommand;
DataTable dt1 = new DataTable();
odjAdp.Fill(dt1);
GridView2.DataSource = dt1;
GridView2.DataBind();
Why is this happening?

Because of the dollar symbol that sheet name needs to be escaped, enclose it in square brackets;
#"SELECT * FROM [Sheet1$]"

Related

The indicated ColumnName 'Data_Mov' does not match any column data source

Trying to import some excel data to sql database, and they have different column names, cause the excel file has special characters and etc...
and I have always this error...
Here's the code:
{
string excelPath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.FileName);
string filename = Path.GetFileName(filepath);
FileUpload1.SaveAs(excelPath);
string ext = Path.GetExtension(filename);
String strConnection = #"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=NO;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$]", excelConnection);
excelConnection.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from [rptListaMovs_4$]", strConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = "Dado";
sqlBulk.ColumnMappings.Add("Data_Mov", "Data Mov.");
sqlBulk.ColumnMappings.Add("Data_Valor", "Data Valor");
sqlBulk.ColumnMappings.Add("Descricao_do_Movimento", "Descrição do Movimento");
sqlBulk.ColumnMappings.Add("Valor_em_EUR", "Valor em EUR");
sqlBulk.WriteToServer(dReader);
}
excelConnection.Close();
}
Error Line:
sqlBulk.ColumnMappings.Add("Data_Mov", "Data Mov.");
I Hope that you guys can help me

in C# using oledb connection string how to Convert Scientific Notation to text strings?

I have a set of data that is downloaded as a Excel file using OLEDB connection string like so:
4552
3.00E+03
3.00E+22
3F45
3.00E+99
DD56677
37
Excel automatically thinks that 3E03, 3E22 and 3E99 are numbers and makes them look like above..
how to get it as a string ?
my code is
DataTable dataTable = new DataTable();
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + strFilePath + ";"
+ "Extended Properties='Excel 8.0;HDR=" + header + ";IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text'";
OleDbConnection connection = new OleDbConnection(strExcelConn);
using (OleDbCommand command = new OleDbCommand())
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
command.Connection = connection;
//Check if the Sheet Exists
connection.Open();
DataTable dtExcelSchema;
//Get the Schema of the WorkBook
dtExcelSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connection.Close();
connection.Open();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
command.CommandText = "SELECT * From [" + SheetName + "]";
adapter.SelectCommand = command;
adapter.Fill(dataTable);
connection.Close();
}
please can any one help me to get this colum as a string
Have a look at this StackOverflow question entitled How to convert a string containing an exponential number to decimal and back to string.
They use the decimal.Parse(someMoneyVar, NumberStyles.Any) method to do the conversion.
Select Excel Columns by name in your query and cast your required columns to a string using CStr(<columnName>)

Unable to read Excel worksheet with OLEDB driver

I have an excel file with one worksheet. I'm using MicroSoft.Office.Interop.Excel to read this file and then perform further execution.
Here is my code:
connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = null;
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
But, worksheet is not in the data table object.
Where you have mentioned the table(WorkSheet) name ??
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
//Get the First Sheet Name
string firstSheetName = schemaTable.Rows[0][2].ToString();
//Query String
string sql = string.Format("SELECT * FROM [{0}],firstSheetName);
Refer here MSDN
In case if you want to play around refer Reading Excel files from C#
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + "; Extended Properties=Excel 12.0;");
//After connecting to the Excel sheet here we are selecting the data
//using select statement from the Excel sheet
oconn.Open();
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
string tbstrat = "M1000";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oconn;
cmd.CommandText = "select * from [" + firstSheetName + "B8:" + tbstrat + "]";
OleDbDataAdapter adap = new OleDbDataAdapter();
DataTable dt = new DataTable();
adap.SelectCommand = cmd;
adap.Fill(dt);
oconn.Close();
Even you can try this
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "NameHere");
DataTable data = ds.Tables["NameHere"];

Im having difficulty setting my OleDb connection

Hi there I am trying to establish a connection to a data source and extract the information and display it in a grid view. The problem is that i always get null value for ada. Is it possible to have mistyped the query or is there something wrong with the adapter?
Furthermore I am using the myInt variable to insert different data sources because i hav to process more than one file, maybe this could be problematic as well.
try
{
//establish connectioin
OleDbConnection conn = new OleDbConnection(("provider=Microsoft.Jet.OLEDB.4.0; " + ("data source=" + myInt + ";" + "Extended Properties=Excel 8.0;")));
OleDbDataAdapter ada = new OleDbDataAdapter("SELECT * FROM MarkingSheet$]", conn);
DataSet ds = new DataSet();
ada.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
conn.Close();
}
ANSWER
Thats what worked for me
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + myPath + ";Excel 12.0;HDR=YES;"); ;
conn.Open();
OleDbDataAdapter ada = new OleDbDataAdapter("select * from [Marking Sheet$]", conn); ;
DataSet ds = new DataSet();
ada.Fill(ds);
Change the sql to
"SELECT * FROM [MarkingSheet$]"
since there's a missing opening bracket.
The Fault in your code is that you havent opened a connection when you attempt to fill the Adapter. Your SQL Statement is also wrong. You may also wan wish to bind the DataTable to the DataGridView too like this :-
try
{
OleDbConnection conn = new OleDbConnection(("provider=Microsoft.Jet.OLEDB.4.0; " + ("data source=" + myInt + ";" + "Extended Properties=Excel 8.0;")));
OleDbDataAdapter ada = new OleDbDataAdapter("SELECT * FROM [MarkingSheet$]", conn);
DataSet ds = new DataSet();
conn.Open();
ada.Fill(ds.Tables[0]);
conn.Close();
BindingSource bs = new BindingSource();
bs.Datasource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch(OledbException x)
{
// Handle Exception
}
EDIT **
Try Changing your connection string to :-
string connString = "provider=Microsoft.Jet.OLEDB.4.0;Data source=" + myInt + ";Extended Properties=Excel 8.0;HDR=Yes;IMEX=1\";";

C# Excel file import to GridView causes OleDB Error

I got an error about OleDB. I just want my excel file import to GridView.
Here is my code.
string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;Extended Properties=Excel 8.0;HDR=YES;IMEX=1";
OleDbConnection conn = new OleDbConnection(connstr);
string strSQL = "Select * from [Sheet1$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
When I build project there is no error, but when I run this project, I got an error like this:
System.ArgumentException:Format of the
initialization string does not conform
to specification starting at index 47.
Line 21: string connstr =
"Provider=Microsoft.Jet.Oledb.4.0;Data
Source=C:\a.xls;Extended
Properties=Excel 8.0;HDR=YES;IMEX=1";
Line 22: Line 23:
OleDbConnection conn = new
OleDbConnection(connstr);
How can I fix this?
\ is a special char in c# string literals.
To specify paths in a string in c# either use escaping:
string path = "C:\\myFolder\\myfile.xls";
or use verbatim strings:
string path =#"C:\myfolder\myfile.xls";
Your string connstr needs double quotes for the Extended Properties values. e.g.:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PrmPathExcelFile + #";Extended Properties=""Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text""");

Categories