How to Read Excel Cell Values With C#

From this post you will be able to learn How to read row data in Excel worksheet or How to find the used area in an Excel worksheet from C#For reading entire content of an Excel file in C#, we have to know how many cells used in the Excel file. In order to find the used range we use "UsedRange" property of xlWorkSheet . It will return the last cell of used area
Excel.Range range ;

range = xlWorkSheet.UsedRange;


Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            Excel.Range range ;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
                    MessageBox.Show(str);
                }
            }

            xlWorkBook.Close(true, null, null);
            xlApp.Quit();

Comments

Popular posts from this blog

Dimensional modeling - Star schema vs Fact constellation

Using Entity Model for connecting the database

Populating data to the Date Dimension table