oledb connection error loading datatable but only on one machine - c#

I'm at a loss. I have this code which runs fine on my machine and loads a csv to a datatable:
public static DataTable GetDataTableFromCsv(string path, string sheetname, string header)
{
var directory = new DirectoryInfo(path);
var myFile = directory.GetFiles().Where(x => x.Name.ToLowerInvariant().Contains(sheetname.ToLowerInvariant())).OrderByDescending(f => f.LastWriteTime).First().Name;
string sql = #"SELECT * FROM [" + myfile+ "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.InvariantCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
this works fine on my machine. On a different machine it does not though. I googled and checked we have the identical version of MSJet40.dll in the same place, we are both on 64bit machines but on the machine where it doesn't work I don't have Visual studio so I can't debug.

Related

Webform only reads headers from a group Excel Files due to the Tab Name

I am building an app to read measurement data (saved as .xls files on our network) from comparators throughout our facility via a Webform. When I query this group of files I only retrieve the headers. My code (pretty standard) will read any other Excel file I can find. I tried to remove a file from the network and save it locally, as well as rename and save it from office 2016. Note - these are .xls files and I can't change that.
** - I just discovered that there are named ranges with the same name as the file. The results I am getting are just the values in the named range and not the data from the workbook.
Here is an example of how they are named (autogenerated) "R87_1RCR0009654S_COIN"
If I rename or remove the named range this works fine.
Is there a way I can change my select statement to read these?
Here is a code sample, not sure there if there is a change I can make here to read these files.
private string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
private string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string conStr, sheetName;
conStr = string.Format(Excel03ConString, info.FullName, "YES");
string fullPathToExcel = info.FullName;
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
}
}
}

Error when trying to load Excel information

I have C# WinForms application that gets information from Excel sheet and stores it to my database, my code works fine on my PC but when I changed it an Error
System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'
display. I solved this problem by changing the project platform from x86 to x64 but when I launch the project with x64 I can't charge many files so I have to run it on x86. Guys any solutions?
Rq: My code:
String name = "Feuil1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
textBox_path.Text +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataview1.DataSource = data;
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UR2k_CS.Properties.Settings.StoreConnectionString"].ConnectionString))
{
String query = "INSERT INTO dbo.Stock (RFID,name,refrence,prix,Stockdate) VALUES (#RFID,#name,#refrence,#prix,#Stockdate)";
connection.Open();
for (int i=0;i<dataview1.Rows.Count-1;i++)
{
using (SqlCommand command = new SqlCommand(query, connection))
{
if ((dataview1.Rows[i].Cells[0].Value.ToString()!=null)&&((!checkifexist(dataview1.Rows[i].Cells[0].Value.ToString()))) &&(dataview1.Rows[i].Cells[0].Value.ToString()!=""))
{
command.Parameters.AddWithValue("#RFID", dataview1.Rows[i].Cells[0].Value.ToString());
command.Parameters.AddWithValue("#name", dataview1.Rows[i].Cells[1].Value.ToString());
command.Parameters.AddWithValue("#refrence", dataview1.Rows[i].Cells[2].Value.ToString());
command.Parameters.AddWithValue("#prix", dataview1.Rows[i].Cells[3].Value.ToString());
command.Parameters.AddWithValue("#Stockdate", DateTime.Now);
command.ExecuteNonQuery();
}
}
}
connection.Close();
}
You need to download the 32 bit driver from here microsoft downloads (I think this is the correct one) but the difficulty you may run into is that a machine cannot have both the 64bit and 32bit versions installed side by side.
Using EPPlus is a more modern approach.

Facing error while loading data from Excel Sheet to DataTable

using (OleDbConnection connection = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
adapter.Fill(dataTable);
}
}
}
The above is the code I am using and getting the below error:
Cannot update. Database or object is read-only.
Have someone faced the same issue?
your connection string contains "Readonly=1;". try changing "Readonly=0;". And try to remove "imex=1". So your code should be someting like that:
using (OleDbConnection connection = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + ";Extended Properties=\"Text;HDR=" + header + ";Readonly=0;Extended Properties=Excel 8.0;\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
adapter.Fill(dataTable);
}
}
}
Try using the following syntax (remove Text from Extended properties since it is used to import csv files) :
using (OleDbConnection connection = new
OleDbConnection(String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"HDR={1};IMEX=1;Readonly=1;Extended Properties=Excel 8.0;\"",pathOnly ,header )))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
dataTable = new DataTable();
adapter.Fill(dataTable);
}
}
}
If you have office 2007 or higher provider installed try using Microsoft.ACE.OLEDB.12.0 provider since the it also support reading old excel formats.
If you are trying to import text files (csv) then it is better to use text parsing libraries such as :
TextFieldParser Class
CsvHelper

OleDb parameter to be used in from clause

I have the following code to read a CSV file and populate a DataTable:
string sql = #"SELECT * FROM [" + fileName + "]";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
This snipped works great, but code analysis complains about it (CA2100). The way I build the query string should be changed so I can use parameters.
I am trying to fix this, but it seems the usual OleDbParameter usage does not work. The query is built with the parameter name instead of its value:
string sql = #"SELECT * FROM #param";
using (OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
{
using (OleDbCommand command = new OleDbCommand(sql, connection))
{
command.Parameters.Add(new OleDbParameter("#param", fileName));
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
}
Any ideas?

Can't connect to excel file unless file is already open

I'm trying to write a class that will read information from an excel file, but for some reason, it will only run exception-free if the file in question is open in excel. Otherwise, the class throws an OleDbException. The code is as follows:
String filename = #"C:\Users\me\Documents\File.xls";
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [Sheet1$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
int counter = 0;
foreach (DataRow row in dt.Rows)
{
String dataA= row["DataA"].ToString();
String dataB= row["DataB"].ToString();
Console.WriteLine(DataA+ " = " + dataB);
counter++;
if(counter>=40)
break;
}
The error is thrown on conn.Open(), and only occurs when I don't have File.xls open in excel at the same time. Can someone help me fix this? I am not well versed enough with OLEDB to figure out why this is happening. Thanks!

Categories

Resources