Error connecting to Excel spreadsheet - c#

Have no idea what I'm doing wrong here but I keep getting the following exception on the connection.Open(); line:
IErrorInfo.GetDescription failed with E_FAIL(0x80004005)
Problem is I have almost the exact same code in another batch job and it works fine. We even pull a spreadsheet from the same location. Does anyone see anything wrong with my connection or query string?
static void Main(string[] args)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= \\prdhilfs03\l&i-sales&mkt\WORKAREA\Agencyservices\Shared\AIC\Analysts_and_Reporting\Realignments\2014\MassUpdateTesting\ZipCodeTest.xslx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [Query1$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connString))
{
//Set connection objects to pull from spreadsheet
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
For good measure here's a screen shot of the workbook I'm trying to connect to

Did you try to check if you can access the file?
string xlFile = #"\\prdhilfs03\l&i-sales&mkt\......\ZipCodeTest.xlsx";
Console.WriteLine(File.Exists(xlFile) ? "Excel File exists." : "Excel File does not exist.");

Related

Read a dbase IV file C#

I am developing an application to recover data from a DBF file.
I did research on the Internet that sent me to this link : enter link description here
I applied this code but nothing helps it doesn't work :/
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test\users.dbf;Extended Properties=dBASE IV;User ID=;Password=MyPassword;";
using (OleDbConnection con = new OleDbConnection(constr))
{
var sql = "select * from users.dbf";
OleDbCommand cmd = new OleDbCommand(sql, con);
con.Open();
DataSet ds = new DataSet(); ;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
I pass this code in a Try and Catch and it returns me this error: Unable to start your application. The workgroup information file is missing or opened exclusively by another user.
the error is caused when trying to open the connection. However the file is neither opened nor used by anyone else.
thank you in advance ;)
Try to remove the file name in the connection string. According to the documentation, The "Data Source" property should only contain the path.
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test;Extended Properties=dBASE IV;User ID=;Password=MyPassword;";

C# ace oledb 12 read-only file

I have a SSIS package with script task. c# script use ACE Oledb 12.0 provider to connect to excel file. The question is, how to connect to excel file in read-only mode (if someone open the file, my script should not have an error - it should work). The code, I tried here:
string fileToTest = Dts.Variables["User::FileName"].Value.ToString();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + fileToTest + #";Extended Properties=""Excel 8.0;READONLY=1""";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open();
string sqlQuery = "SELECT * FROM [SheetName$A1:FZ1000]";
OleDbDataAdapter dataAdt = new OleDbDataAdapter(sqlQuery, excelConnection);
DataSet dataSt = new DataSet();
dataAdt.Fill(dataSt, "TblName1");
DataTable dataTbl = dataSt.Tables["TblName1"];
I receive oledbexception, if someone open the file.
Use google to search for that.
I searched for: "microsoft.ace.oledb.12.0 read only"
https://social.msdn.microsoft.com/Forums/office/en-US/498cd52a-b0ee-4c8d-8943-2b76055b4130/oledbconnection-read-only-mode?forum=accessdev
It looks like you can add to the connection string.
From that page:
Actually, with an OleDbConnection (assuming .net here). You can specify a read only mode in your connection string of the OleDbConnection. The following connection string will prevent you from changing data in your datasource:
const string cnnString = "Provider=Microsoft.ACE.OLEDB.12.0"
+ ";Mode=Read"
+ #";Data Source=|DataDirectory|\Northwind 2010.accdb";
It looks like adding ;Mode=Read to the connection string should do the trick.

alternate for Oleb DB importing excel file

Maybe someone can help me with the following problem:
I want to import a excel file and read the columns in to the database. I used OleDB provider so far:
string constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
using (OleDbConnection conn = new OleDbConnection(constr))
{
conn.Open();
OleDbCommand command = new OleDbCommand("Select * from [Sheet1$]", conn);
OleDbDataReader reader = command.ExecuteReader();
is there an alternate for doing this without OleDB? im getting the following errormessage:The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. and i dont have the option to install ole DB on the environment where the application is running.
thanks

Getting different errors while importing Excel file through SqlBulkCopy

I am importing an Excel file into SQL Server using SqlBulkCopy
But every time I get differant errors like
Cannot update. Database or object is read-only.
or
Could not find installable ISAM.
or
The Microsoft Jet database engine could not find the object. Make sure the object exists and that you spell its name and the path name correctly.
Check my code below...
String strConnection = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filepath+";Extended Properties=Excel 8.0;HDR=YES;";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select * from [Sheet1$]",
excelConnection);
MessageBox.Show("ss");
excelConnection.Open();
MessageBox.Show("ss2");
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
MessageBox.Show("ss1");
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "RecExcelTable";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
Also I need to compitable this code for any version of Excel.
How can I do that and solve my error?
I had similar issue. Check that the file path is correct
do like
C:\\file.xls
as a test.
And also check that the version is correct. 8.0 is pretty old I think thats like office 2000, no ?

How can I connect to a SDF database? No connection string I try seems to work

I've tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. I'm essentially just trying to open a connection the database file so I can dump in the data I've pulled out of my excel spreadsheet. I'm using Visual C# making an offline winform application.
No matter what connection string I try in my app.config, it always fails when it tries to write "dReader" to the database.
The error is usually this depending on what string I try:
"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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
I've gone through many online examples and resources and none seem to work. I'm hoping someone here can point out why it's failing.
Here is my app.config in its latest form:
<connectionStrings>
<add name="DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"
connectionString="Data Source=E:\Other DDP Projects\DDP_Project_SDF\DDP_Project\DDP_Database.sdf;"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Here is my form code:
private void Profiles_Click(object sender, EventArgs e)
{
profilesDialog.FileName = "[YOUR_UPLOAD_FILE_HERE]";
var result = profilesDialog.ShowDialog();
if (result == DialogResult.OK)
{
HandleFileSelection();
}
}
private void HandleFileSelection()
{
var file = profilesDialog.FileName;
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\DDP_Database.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
//Create connection string to Excel work book
string excelConnectionString = string.Format(
#"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=""{0}"";
Extended Properties=""Excel 8.0;HDR=YES;""", file
);
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT [ID],[STATUS],[FAN_NUM],[PROFILE_NAME],[DESTINATION_HOST],[USER_ID],[USER_PASSWORD],[PROTOCOL],[PORT],[PATH],[CONTACT_NAME],[CONTACT_EMAIL],[CONTACT_PHONE],[CONTACT_ALT_PHONE],[CONTACT_CITY],[CONTACT_STATE],[CONTACT_CONTACT_TIME] FROM [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Profiles";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("STATUS", "STATUS");
sqlBulk.ColumnMappings.Add("FAN_NUM", "FAN_NUM");
sqlBulk.ColumnMappings.Add("PROFILE_NAME", "PROFILE_NAME");
sqlBulk.ColumnMappings.Add("DESTINATION_HOST", "DESTINATION_HOST");
sqlBulk.ColumnMappings.Add("USER_ID", "USER_ID");
sqlBulk.ColumnMappings.Add("USER_PASSWORD", "USER_PASSWORD");
sqlBulk.ColumnMappings.Add("PROTOCOL", "PROTOCOL");
sqlBulk.ColumnMappings.Add("PORT", "PORT");
sqlBulk.ColumnMappings.Add("PATH", "PATH");
sqlBulk.ColumnMappings.Add("CONTACT_NAME", "CONTACT_NAME");
sqlBulk.ColumnMappings.Add("CONTACT_EMAIL", "CONTACT_EMAIL");
sqlBulk.ColumnMappings.Add("CONTACT_PHONE", "CONTACT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_ALT_PHONE", "CONTACT_ALT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_CITY", "CONTACT_CITY");
sqlBulk.ColumnMappings.Add("CONTACT_STATE", "CONTACT_STATE");
sqlBulk.ColumnMappings.Add("CONTACT_CONTACT_TIME", "CONTACT_CONTACT_TIME");
sqlBulk.WriteToServer(dReader);
sqlBulk.Close();
excelConnection.Close();
}
private void profilesDialog_FileOk(object sender, EventArgs e)
{
}
}
}
Try this...
First:
Create first a test method which you may check if you can connect to sqlcedatabase.
private void testconnection()
{
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
using (var conn = new SqlCeConnection(string.Format("Data Source={0};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;", strConnection)))
{
conn.Open();
try
{
//your Stuff
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Second:
Just Load your excel file Data into a Datatable and use foreach then save it on your sql ce database file..
//Something like
//oledbcon
//oledb dataadapter
//datatable
// dapt.Fill(dt);
foreach(DataRow excel in dt.Rows)
{
ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
ceCmd.ExecuteNonQuery();
}
Regards
I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. You create the connection using this but then you don't use it. Instead you pass in the connection string to the SqlBulkCopy object which implicitly creates a SqlConnection from that string. I'm assuming it is on that line where you are getting the error. If you notice the namespace of the SqlBulkCopy is System.Data.SqlClient. The reason you are seeing the error is that its trying to go through SQL Server to make the connection and cannot resolve your connection string to a SQL Server database. Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. Stick to using classes in System.Data.SqlServerCe and things should work as expected. You just will have to do the processing in a more manual fashion.
According to this post, SqlBulkCopy isn't supported with SqlCe.

Categories

Resources