A colleague of mine was trying to do something really simple,read an excel file programatically:
There are 3 ways to do this using C#:
1)Add a reference to the Excel Object library and use the Accessor class.
2)Use the data binding mechanism already provided in Visual Studio.
3)Use the OLEDB class to run SQL queries on it.
If you are a lazy programmer who hates writing too many lines of junk code and who would rather spend a bit more time in figuring out an easy way of doing things then the first method strikes out, itz a lot of functions and a lot of properties.
The second one is the easiest to implement and use but gives you almost no flexibility.So that one is crossed out too.
I personally liked and implemented the third approach why?? simple easy instinctive.
An excel sheet is a like a database,every sheet inside it is like a table and the name of the header is like the name of column.
So if I have a an excel sheet called Jobs.xlsx where first sheet is called Emps and i would wanna have the employeed ids which is the 5th column and has a header called ids, I just have to say:
[Select ids from Emps$]
Here is the sample code:
string conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + @"D:\s.xlsx" + @";Extended Properties=""Excel 12.0 Xml;HDR=YES;""";
OleDbConnection connection = new OleDbConnection(conn);
connection.Open();
OleDbDataAdapter dataadapter1 = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", connection);
dataadapter1.SelectCommand = cmd;
DataTable tbls = new DataTable("aa");
dataadapter1.Fill(tbls);
DataRow dr = tbls.Rows[1];
object[] obj = dr.ItemArray;
So because I had done this earlier, so I just sent over my code to my colleague.
The code crashed in the 3rd line:
connection.open();
>.NET exception:Couldn't find installable ISAM.
Whoa itz running on my machine then why not his and wat the hell is ISAM, huh.
The first thing that we do when something puzzles us is search:
But guyz here don't look at the results returned by the search, it will talk about unchecking just my code in System properties,it will talk about two Jet OleDb providers present in your machine blahblahblah.
The remedy is just check your Connection String.
If you have problems with connection strings which probably every developer has u can visit,http://www.connectionstrings.com/
The connection string is consumed first but validated later by the compiler, and when it does it doesn't know what to do as it doesn't have a base value to validate with probably.So what does it do, pops out the last message from the error queue. HUH.
It's funny even today in the age of super duper compilers and debuggers we still have errors and exceptions which are handled so badly.
Monday, 16 March 2009
Subscribe to:
Comments (Atom)
