Read Excel using c# .net Issue - c#

I read data from excel sheet using C#.
Here is my code and it is working.
var fileName = #"C:\Users\yohan\Desktop\Brandix\y.xlsx";
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source= {0}; Extended Properties=Excel 12.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [BOM$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds);
DataTable data = ds.Tables[0];
But it always skip the top row of the excel sheet why is that ?
Please help ...!!
Thank You
yohan

That is the normal behaviour of the DataAdapter. The top row is considered as an Header Row or a "Column Name" Row.
To change this behaviour add to the Extended Properties of your connection string the property "HDR=NO"
Example:
var fileName = #"C:\Users\yohan\Desktop\Brandix\y.xlsx";
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=""Excel 12.0;HDR=NO;""", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [BOM$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds);
DataTable data = ds.Tables[0];

Try adding HDR=NO to the extended properties.
see this link for details

Try changing your connection string to ...
"Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=\"Excel 12.0;HDR:No\""
See this page for more possible connection strings to try. The HDR setting determines wether the provider considers the top row to be column names.

Recommended way to read an Excel file in Server side app is Open XML.
You can try installing ACE component but still it remains un-recommended and unsupported.
For using Open XML you can go through below links which will help you using Open XML in your code for reading excel files -
Link1
Link2
Link3

Related

IErrorInfo.GetDescription failed with E_FAIL(0x80004005) in asp.net c#?

I am trying to read an excel file and convert the contents of the file to a datatable but I keep getting this exception IErrorInfo.GetDescription failed with E_FAIL(0x80004005) pointing at a specific line POCCommand.Fill(dt);This is what I tried so far. What could I be doing wrong ?
string POCpath = #"p.xlsx";
string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
First, since you're using .NET, you need to wrap anything that inherits or implements from IDisposable into a using statement.
such as:
using (OleDbConnection connection = new OleDbConnection("connectionstring")){
//Do stuff here
}
Second:
Please refer to this great answer by MethodMan on this SO Answer.
It has everything you will need to know. He does both OleDb connections and a TextFieldParser which will be faster and less expensive.

Excel sheet to SQL table

I get the Excel sheet with data uploaded from UI, I need to access that sheet through WCF service and insert the data contained in it into a SQL table.
Kindly guide how this can be done.
I am facing challenge in reading that Excel sheet through WCF service.
I have used below code to read a Excel sheet from a local drive. Change Source property to your FTP location of your excel sheet.
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MyData.xlsx;" +
#"Extended Properties='Excel 8.0;HDR=Yes;'";
using (OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using (OleDbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
// Do your things here
}
}
}
Note: .xls has data limitations whereas .xlsx supports more data rows in a sheet. You need to install Microsoft Office Access database engine 2007 if you are going to read .xlsx files
string UploadedFilePath = FullPathOfExcelOnTheServer;
string ExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + UploadedFilePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1;FMT=Delimited\"";
using (OleDbConnection oledbConnExcel = new OleDbConnection(ExcelConn))
{
oledbConnExcel.Open();
using (OleDbDataAdapter oledbAdapterExcel = new OleDbDataAdapter("SELECT * from [" + SheetName + "$]", oledbConnExcel))
{
using (DataTable dtblSheetData = new DataTable())
{
try
{
oledbAdapterExcel.Fill(dtblSheetData);
}
catch (Exception lexQuery)
{
}
}
}
oledbConnExcel.Close();
}
Fact is the is no way to read the excel data through WCF Service. But You can cosider this approaches
You may:
Read all excel data on client side and call WCF service and include all data from excel in parameter as (array of strings)?
You can create macro(VB) in Excel sheet and what call WCF Service and send data through parameter. When You have all logic in one place.
If client side is .NET side You can use atribbute [KnowsTypeAtribbute].Then You can call WCF service with param type as Excel type (Sheet or other). May by use some type form OpenXml dll may by usefull (But I don't know is sheet or other types is serializable. A serializable is require)
You can send to WFC service path to file and read excel file from that path through WCF service.

How can I read Excel file? [duplicate]

This question already has answers here:
Excel "External table is not in the expected format."
(25 answers)
Closed 7 years ago.
I want to read excell file with this code:
var fileName = #"d:\1.xlsx";
var connectionString = string.Format(
"Provider=Microsoft.Jet.OLEDB.4.0; data source="+fileName+
"; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
DataTable data = ds.Tables["anyNameHere"];
But when run the program I get this error:
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: External table is not in the expected format.
How can i solve that?
Your excel file is 2007 version, *.xlsx and you are using the wrong provider(Microsoft.Jet.OLEDB.4.0).
Try this approach:
var fileName = #"d:\1.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;";
Its already answer the question in the past post Please follow the below link
Answer link
The answer is very simple
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Test.xlsx;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
you have diff version of Excel file, get the file name, if its extension is .xlsx, use this
var fileName = #"d:\1.xlsx";
var connectionString = string.Format(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="{0}";Extended Properties=Excel 12.0;", fileName);
I would suggest this Libary called FileHelpers. Since discovering it i have never written the plumbing code myself. It lets you concentrate on the actual business logic.

Updating data in to a Excel sheet using c#

I am trying to update some data in an Excel sheet of the format "xlsx" using OLEDB connection, but I am unable to make out the connection establishment.
Here is my code:
String sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + "D:\abc1.xlsx" + "';Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection con = new OleDbConnection(sConnectionString);
con.Open();
OleDbCommand com = new OleDbCommand("select * from Sheet1",con);
OleDbDataReader reader = null;
reader = com.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
con.Open();
Console.ReadLine();
}
When I run the code, I'm facing the following exception:
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local
machine.
Any idea how to recover from this exception or any other suggestions from which i can update my data in excel is advisable.
This could be the provider you have stated try changing it to the one which matches the Excel version on your machine
Try
Provider=Microsoft.ACE.OLEDB.12.0;Data Source='D:\abc1.xlsx';Extended Properties="Excel 12.0 Xml;HDR=YES";
Instead
Could also be that excel isnt installed
Also check that you have referenced the OLEDB library for your project
Change your PlatformTarget Type from AnyCPU to X86.
Steps:
Goto Project Properties.
Select Build tab.
Select X86 from PlatformTarget options.
It is possible that there are multiple reasons for this exception.
1) You could use the OleDbEnumerator class to find out what providers are available.
Accordingly you set your connection string.
2) Before that just try out below connection string.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + "D:\abc1.xlsx" + "';Extended Properties='Excel 8.0;HDR=Yes'";
3) If you have a 64 bit OS, there is no 64-bit version of the JET provider available and there's no alternative. As long as you want to support JET, you'll need to set the build target to x86.
first save as your excel workbook as Excel 97-2003 Workbook
It will work in my project...
string filepath = Server.MapPath("~/ImportData/") + fileUpload.FileName;
OleDbConnection oconn = new OleDbConnection
(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";
Extended Properties=Excel 8.0");`
oconn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter("select * from Sheet1", oconn);
DataSet ds = new DataSet();
adp.Fill(ds);
oconn.Close();`

Major issues working with XLS in c# .net 4.0

I have an xls file i would like to read using c# and populate the information in a data table. The code I am using is :
public static DataTable GetExcelData(string excelFilePath)
{
OleDbConnection objConn = null;
string oledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=Excel 10.0;";
objConn = new OleDbConnection(oledbConnectionString);
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
var objCmdSelect = new OleDbCommand("Select * from [Sheet1$]", objConn);
var objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
var objDataset = new DataSet();
objAdapter.Fill(objDataset, "ExcelDataTable");
objConn.Close();
return objDataset.Tables[0];
}
Once this data table is populated, I need to remove the first 5 or so rows which contain header information, and loop through the data table populating an access database table. I have had no luck with this or any of the other 10,000 ways suggested. Does anyone have any information that can help me. I am running VS2010 .net 4.0 framework. Any and all help would be super appreciated.
Thanks,
John
I've had a great deal of trouble trying to get Excel data into a DataTable using OLEDB. I finally solved the issue by switching to a solution that uses Excel Interop. Please see this answer for further explanation and sample code:
Importing from Excel: some cells become null

Categories