Facing error while loading data from Excel Sheet to DataTable - c#

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

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();
}
}
}

C# Tabdelimited text File with multiple column and multiple values in column to datatable

I am trying to convert my text file having TabDelimited data to Datatable, Text file data shown below:
Row1Col1 Row1Col2 Row1Col3 Row1Col4_0
Row1Col4_1
Row1Col4_2
Row2Col1 Row2Col2 Row2Col3 Row2Col4
Row2Col2
My code for conversion:
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.DirectoryName + ";Extended Properties='text;CharacterSet=" + characterSet + ";HDR=No;FMT=TabDelimited';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", file.Name), con))
{
con.Open();
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable tbl = new DataTable("MyTable");
adp.Fill(tbl);
}
}
}
It's showing me multi line value of column into different column.

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?

oledb connection error loading datatable but only on one machine

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.

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