Link to home
Start Free TrialLog in
Avatar of lancerxe
lancerxe

asked on

Reading an Excel file in C#

Hello experts:
I'm trying to load the load test.xls contents thru c# code so that I can update some data base fields:
My code is below:

public class BankParserClass

Excel.Application excelApp = new Excel.ApplicationClass();

Excel.Workbook newWorkbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
( this line of code gets an error    here on excelApp : denotes a fileld where a class is expected)                                                  

string workbookPath = "c:/test.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
      0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
      true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
      string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
Excel.Range excelCell =(Excel.Range)excelWorksheet.get_Range("A1", "A1");

I got other errors but I think they are related to the 1st error above.  

Thanks
Avatar of Yurich
Yurich
Flag of New Zealand image

have you added a reference to your application? I mean "Microsoft Excell 9.0 (or 10.0) Object Library"?

regs,
yurich
ASKER CERTIFIED SOLUTION
Avatar of alpesh_mca
alpesh_mca
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HarryNS
HarryNS

There is one easy of reading excel file from .Net application.

string strFilePath = "C:\A.xls";
string excelConnectionString = "Dsn=Excel Files;dbq=" + strFilePath + ";defaultdir=" + ";driverid=790;maxbuffersize=2048;pagetimeout=5";
                    //Load Open detals
                    using (OdbcConnection connection = new OdbcConnection(excelConnectionString))
                    {
                        try
                        {
                            connection.Open();

                            OdbcCommand command = new OdbcCommand("Select [ID], [Status],[Created] FROM [Open$]", connection);
                            OdbcDataAdapter da = new OdbcDataAdapter(command);
                            da.Fill(dsSummary, "Open");

                            connection.Close();
                        }
                        catch
                        {
                            connection.Close();
                        }
Calling Com services is very slow process becaue it is remote procedure call .
 opening OBdc connection or OLedb  is an effeicent way you can easily filter data as want but in
excel object it iterate row by row and cause increase in condition or check you apply for filter.
In calling Excel object cause some problem while closing its object , if program breaks without closing excel
object it remain open until you by force kill them from task manager.