OleDbConnection Source Variable in C# - c#

How can I replace D:\temp\test.xls with filePath in OleDbConnection statement.
I can get the exactly filePath (with OpenFileDialog, then I can located my .xls file conveniently, no more hardcoded), but when I insert the variable filePath as Style2, it doesn't work. How can I fix this ? Thanks.
Style1
OleDbConnection dbConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;Extended Properties=""Excel 8.0;HDR=Yes;""");
Style2
OleDbConnection dbConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filePath;Extended Properties=""Excel 8.0;HDR=Yes;""");
[Updated]
Some part of my code as this,
DataTable fooData = new DataTable();
OleDbConnection dbConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filePath;Extended Properties=""Excel 8.0;HDR=Yes;""");
dbConnection.Open ();
try
{
OleDbCommand dbCommand = new OleDbCommand("SELECT * FROM [maleSheet$]", dbConnection);
OleDbDataReader dbReader = dbCommand.ExecuteReader();
int RankIndex = dbReader.GetOrdinal("Rank");
while (dbReader.Read())
{
string rank = dbReader.GetValue(RankIndex).ToString();
////....
}
}
Error as below at line OleDbDataReader dbReader = dbCommand.ExecuteReader();
An unhandled exception of type
'System.Data.OleDb.OleDbException'
occurred in System.Data.dll

OleDbConnection dbConnection = new OleDbConnection( String.Format( #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;""", filePath ) );

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

Exception on Open in OleDbConnection

When I am trying to open a excel into one of my windows service using following code it is throwing "Value cannot be null. Parameter name: source" on objConn.Open(); Can any one please help me.
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
LogManager LogWrite = new LogManager();
try
{
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Repository\RuleExcel\Rules_Repository_2018-06-28_03-41-29-133.xlsx;Extended Properties='Excel 12.0;HDR=YES;';";
LogWrite.WriteLog(conn);
// Create connection object by using the preceding connection string.
objConn = new OleDbConnection(conn);
LogWrite.WriteLog(objConn.DataSource);
// Open connection with the database.
objConn.Open();
try this below code, it works for me :
using (OleDbConnection objConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + #";Extended Properties=""Excel 12.0;IMEX=1;HDR=YES;"""))
{
objConn.Open();
}

C# Import Excel Data to SQL Table

I am trying to use a method I pulled off of CodePlex, which exports data from Excel into a SQL table. I have made some minor code adjustments, but I still can't seem to get the data to import. Does anyone see anything glaringly wrong with my syntax? Thanks.
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select Name,EmployeeID from [sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + excelfilepath + ";Extended Properties=" + "\"excel 8.0;hdr=yes;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlcmd.Connection.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
The problem is here:
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
The while (dr.Read()) block is useful if you are iterating over the results one-by-one.
But it's not you who is iterating over the results. You want the bulk copy operation to do the iterating.
Simply replace it with
bulkcopy.WriteToServer(dr);
This should work for you.
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
For more info, see the links below.
https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh
http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/
As you can tell, there are MANY ways to do what you want to do.

Excel Loading via c#

Try to Load an excel file using this code below gives me this error
The Microsoft Access database engine could not find the object 'Sheet Name'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet Name' is not a local object, check your network connection or contact the server administrator.
i am sure the Sheet Name is correct.
Any suggestions?
if (strFile.Trim().EndsWith(".xlsx"))
{
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if (strFile.Trim().EndsWith(".xls"))
{
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "]";
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
///error in this line
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
As mentioned in a comment above have you tried this
string sql = "SELECT * FROM [" + sheetName + "$]";
DataSet ds = new DataSet();
if (strFile.Trim().EndsWith(".xlsx"))
{
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if (strFile.Trim().EndsWith(".xls"))
{
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection objXConn = new OleDbConnection(strConnectionString);
objXConn.Open();
OleDbCommand objCommand = new OleDbCommand("SELECT * FROM [" + SheetName + "$]", objXConn);
OleDbDataAdapter adp = new OleDbDataAdapter(objCommand);
adp.Fill(ds);
objXConn.Close();

Syntax error when opening an Excel workbook using 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$]"

Categories