12 Temmuz 2012 Perşembe

reading an excel file in C#

In order to read an excel file cell by cell, the first step is adding Microsoft Excel Object Library as a reference to the project (http://www.c-sharpcorner.com/Forums/Thread/80161/). 
Afterwards, the following code should work:

// ..
using Excel = Microsoft.Office.Interop.Excel;
// ...

 private static void ReadExcelFile()
 {
            Excel.Application exApp ;
            Excel.Workbook exWorkBook ;
            Excel.Worksheet exWorkSheet ;
            Excel.Range range ;


            string str;
            int row = 0;
            int column = 0;


            String pwd =  Directory.GetCurrentDirectory();


            exApp = new Excel.Application();
            exWorkBook = exApp.Workbooks.Open("C:/filename.xls" );
            exWorkSheet = (Excel.Worksheet)exWorkBook.Worksheets.get_Item(1);


            range = exWorkSheet.UsedRange;


            for ( row  = 1;  row  <= range.Rows.Count; row++)
            {
                for ( column = 1;  column <= range.Columns.Count;  column  ++)
                {
                    // to allow nullable cells
                    if (range.Cells[rCnt, cCnt].Value2 == null) continue;
                    str = range.Cells[row,  column].Value2.ToString();
                }
            }


            exWorkBook.Close(true, null, null);
            exApp.Quit();
}


see these for more:
http://csharp.net-informations.com/excel/csharp-read-excel.htm
http://dontbreakthebuild.com/2011/01/30/excel-and-c-interop-with-net-4-how-to-read-data-from-excel/

Hiç yorum yok:

Yorum Gönder