Can't read from my Excel file using C# - c#

I have an Excel 2007 file "my.xlsx" and a sheet named "States", and I have the following code
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\my.xlsx;Extended Properties='Excel 12.0 Xml;HDR=NO'"))
{
OleDbCommand cmd = new OleDbCommand("select * from [States]", con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
Console.WriteLine(reader[0]);
}
It keeps throwing exception saying "The Microsoft Office Access database engine could not find the object 'States'. Make sure the object exists and that you spell its name and the path name correctly.".
Could someone help to see what's wrong with my code please?

I know this may be not exactly what you want to hear, but you're in a long line of people who have had struggles trying to read excel files by using oledb...
I've had a lot more luck using libraries such as NPOI to read Excel files from C#:
http://npoi.codeplex.com/ (recommended)
http://nexcel.sourceforge.net/
http://sourceforge.net/projects/koogra/

I think that you need to open the connection before creating the command - not sure if it's a big deal...
Then add a $ at the end of the sheet name:
OleDbCommand cmd = new OleDbCommand("select * from [States$]", con);
Basically [Name] refers to a named range, whereas [Name$] refers to a sheet.
For more information see this KB: http://support.microsoft.com/kb/316934

I just got it working by visiting this page
http://www.davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx
For my requirement, I only need to read an Excel file. Most of the solutions I searched show you to use some kind of library, which is overkill for me. I was really looking for someone to just post a code snippet on how to read the file, but I only found that on the page I put the link with.

Related

How to read data from excel file using c# [duplicate]

This question already has answers here:
Reading Excel files from C#
(32 answers)
Closed 9 years ago.
My application needs to read data from an excel file. I am using .Net and c# for development.
I cannot install MS office in the system. Because of that the my application fails to read excel file and throws an error while loading the dll for excel.
How can i access excel file in my application in a system where ms office is not installed?
There is the option to use OleDB and use the Excel sheets like datatables in a database...
Just an example.....
string con =
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +
#"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())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
This example use the Microsoft.Jet.OleDb.4.0 provider to open and read the Excel file. However, if the file is of type xlsx (from Excel 2007 and later), then you need to download the Microsoft Access Database Engine components and install it on the target machine.
The provider is called Microsoft.ACE.OLEDB.12.0;. Pay attention to the fact that there are two versions of this component, one for 32bit and one for 64bit. Choose the appropriate one for the bitness of your application and what Office version is installed (if any). There are a lot of quirks to have that driver correctly working for your application. See this question for example.
Of course you don't need Office installed on the target machine.
While this approach has some merits, I think you should pay particular attention to the link signaled by a comment in your question Reading excel files from C#. There are some problems regarding the correct interpretation of the data types and when the length of data, present in a single excel cell, is longer than 255 characters
CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats
Good luck!
Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.
I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:
using System.Data;
using System.Data.OleDb;
namespace Data_Migration_Process_Creator
{
class Class1
{
private DataTable GetDataTable(string sql, string connectionString)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
private void GetExcel()
{
string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);
foreach (DataRow dr in dt.Rows)
{
//Do what you need to do with your data here
}
}
}
}
Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.
Convert the excel file to .csv file (comma separated value file) and now you can easily be able to read it.

Reading A Fixed Format Text File

Its been years since I have had to attempt to read a file using either Microsoft Text ODBC Driver or Microsoft Jet OLE DB 4.0 Provider.
So I have the following code
public void Example()
{
string CVS = Application.StartupPath;
string SQL = "SELECT * FROM [MyFile.txt]";
string Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+CVS+";"+"Extended Properties='text;HDR=Yes;FMT=Fixed;";
OleDbDataAdapter OLE = new OleDbDataAdapter(SQL,Connection);
DataTable Table = new DataTable();
OLE.Fill(Table);
}
When I run the above code I get an "Unexpected Error", I know I am missing something, I am not sure what exactly.
Sources:
http://www.connectionstrings.com/textfile
http://www.connectionstrings.com/Providers/net-framework-data-provider-for-ole-db
http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx
Any direction would be appreciated.
Let us assume the Schema.ini file is correct.
Remove ' (just prior to 'text;) from the connection string.
In order to resolve the "Could not find installable ISAM", run the following command:
Regsvr32 c:\winnt\system32\mstext40.dll
* Make sure that file is in that folder first. And change WINNT to whatever your windows directory is.
I know this is not a real answer to your question, but i would really rethink about using this architecture to read in a file.
I would really prefer something like CSV Reader, cause it gives you much more power about how the data will be interpreted. Alternative you could also take a look into the FileHelpers.

C# read open Excel file through OleDb

I need to connect to an open Excel 2003 file using .NET 3.5
It seems the OleDb connection which I am trying to use wants the file exclusively. But I need to have this file open in Excel in the same time.
Is non-locking reading possible?
EDIT: I resolved this by copying file before opening it.
the question seems have no answer. and I cant delete it....
my solution was - run macro on timer to save the excel file in question and C# app was copying the file to another one and reading it using OleDb.
This seems like a similar problem:
Writing into excel file with OLEDB
Does that work out for you?
What parameters are you passing in when you open the Excel document? Could you set the "ReadOnly" parameter in Workbook.Open() to true? See here.
Refer to the code below how to get the information of Excel data into an array. Then you will perform any validations on that Excel sheet.
var fileName = #"D:\Pavan\WorkDiployed.xlsx";
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 12.0;", fileName);
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
DataTable data = excelDataSet.Tables[0];
DataRow[] arrdata = data.Select();
foreach (DataRow rw in arrdata)
{
object[] cval = rw.ItemArray;
}
con.Close();
MessageBox.Show (excelDataSet.Tables[0].ToString ());

C# 3.5 Reading Excel files

I have a strange behavior when i try to read an XML worksheet using this code :
string CONNEC_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=No;IMEX=2;\"";
string fullFilePath = #"C:\Tmp\TestFile.xls";
using (OleDbConnection objCon = new OleDbConnection(string.Format(CONNEC_STRING, fullFilePath)))
{
using (OleDbCommand cm = new OleDbCommand("Select * From [MYCELLSRANGE]", objCon))
using (OleDbDataAdapter da = new OleDbDataAdapter(cm))
{
DataTable dt = new DataTable();
objCon.Open();
da.Fill(dt);
objCon.Close();
}
}
If the Excel file is closed, I receive the error 'External table is not in the expected format.'
When I open the file, if I execute the above code, it works fine and I can read data contained in MYCELLSRANGE.
So, has anyone any idea about this problem ?
Thanks for answers.
I believe its because the Jet Engine uses the Excel app to interpret the file. I ran into this issue once myself. When you use the Excel.dll reference and you interpret the Excel file from that you have to create a new Application instance to read the file. Jet just does this very thing to get the data. I suggest using that code instead.
C# Corner example of how to Import Excel to a ListView
C# Corner example of how to Create an Excel Worksheet in C#
MSDN users discussing the same topic
If you would like further assistance, let me know. I have successfully done this in VB.NET in various applications of mine.

opening excel file via c# application

My application using excel file in order to read data from web (using excel web query and reading the data from the excel file)
The excel file I'm using called webGate.
my problem is that I don't want webGate to be presented to the user.
if the user opens excel file (any other file) while my application is reading the webGate file the webGate file is presented with the user file
(i.e. user opens excel file and two files are being presented one of them is the webGate)
Any idea about how can I use the file but it will never be presented to the user?
Thanks
Eran
What do you want to achieve? Its is unclear.
Any idea about how can I use the file but it will never be presented to the user?
If you want to open/modify the file in C# code:
http://www.codeproject.com/KB/office/csharp_excel.aspx
You can use an .xls as a OLEDB data source. You use the Microsoft.Jet.OLEDB.4.0 data provider.
This means you are reading the data out of the excel sheet, rather than opening the .xls as a document in the Excel application.
It is not automation. It does not start Excel.exe. It does not require Excel.exe. There is no third-party component required. There's no additional cost (beyond the cost of Windows). It works in server-side apps.
Full source code here.
Snippets:
void CreateExcelDocThroughAdoNet()
{
const string Filename= "adonet-excel.xls";
const string strConnect =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Filename + ";" +
"Extended Properties=\"Excel 8.0;HDR=yes;\"";
try
{
conn = new System.Data.OleDb.OleDbConnection(strConnect);
CreateTable();
for(int i=0; i < 4; i++) Insert(i);
}
catch (System.Exception ex)
{
System.Console.WriteLine("Exception: " + ex.Message+ "\n " + ex.StackTrace);
}
}
private void CreateTable()
{
string strSql = "CREATE TABLE SampleTable ( Ix NUMBER, CustName char(255), Stamp datetime )";
System.Data.OleDb.OleDbCommand cmd= new System.Data.OleDb.OleDbCommand(strSql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
private void Insert(int ix)
{
string strSql = "insert into [SampleTable] ([ix],[CustName],[Stamp]) value(#p1,#p2,#p3)";
System.Data.OleDb.OleDbCommand cmd= new System.Data.OleDb.OleDbCommand(strSql, conn);
cmd.Parameters.Add("#p1", System.Data.OleDb.OleDbType.Numeric).Value = ix;
cmd.Parameters.Add("#p2", System.Data.OleDb.OleDbType.VarChar).Value = "Some text";
cmd.Parameters.Add("#p3", System.Data.OleDb.OleDbType.Date).Value = System.DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
I don't know if this would be too much trouble or not, but it might be worth it to export the excel file as an xml (if this is possible, I don't know what your excel file looks like) and read the data in that way.
I use the Infragistics toolset for this purpose, and it works great (supports all excel versions, and is very feature rich)
It may not suit your needs because it's not free, but it's largely worth its cost if you ask me
If the project will take less than 30 days, you can use the free evaluation of SpreadsheetGear for .NET to embed an Excel workbook in a .NET application without it being presented to the user. Just follow these steps:
Create a new C# Windows Forms application and put a WorkbookView control on your form (see the SpreadsheetGear Tutorial for Windows Forms app if your not sure how to do this).
Right click on the WorkbookView and chose "Workbook Designer...".
In the Workbook Designer, close the default workbook and use File Open... to open your workbook. This will embed your workbook in the application as a resource.
Close the Workbook Designer.
You can hide the WorkbookView if you don't want the user to see it, or you can use the WorkbookView.DisplayReference property to limit what parts of the workbook they can see.
You can download the free evaluation here.
Disclaimer: I own SpreadsheetGear LLC

Categories