Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all the cell values from an Excel range in C#

Tags:

c#

Suppose I have range from E2 to E16. How do I read values from cells E2 to E16?

like image 213
Sathish Avatar asked Apr 13 '10 06:04

Sathish


People also ask

How to Get values from a range of cells?

If you want to retrieve values from a range of cells, use the GetRange and GetRangeA1 methods instead. Methods that have the A1 suffix ( GetCellA1 and GetRangeA1) use a different coordinate system than those that do not ( GetCell and GetRange).

How do you read cell values in Excel?

We can get the value of a cell (its content) by using the INDEX Function. The INDEX Function looks up a cell contained within a specified range and returns its value. In the example above, the range specified in the INDEX formula is “A1:J10”, the row is cell “C3” (“3”), and the column is cell “C4” (“5”).

How do you check if a cell is empty in Excel using C#?

Range xlCell; do { rCnt++; str = "A" + rCnt; xlCell = (Excel. Range)xlWorksheet. get_Range(str, str); } while (xlCell. Value2 == null);


1 Answers

You can try somethinfg like this. it should work

U can specify ur range as u wish inside.

this.openFileDialog1.FileName = "*.xls";
  if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
   {
      Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
         openFileDialog1.FileName, 0, true, 5,
          "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
          0, true); 
     Excel.Sheets sheets = theWorkbook.Worksheets;
     Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
     for (int i = 1; i <= 10; i++)
     {
     Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
     System.Array myvalues = (System.Array)range.Cells.Value;
     string[] strArray = ConvertToStringArray(myvalues);
     }
}

string[] ConvertToStringArray(System.Array values)
{ 

// create a new string array
string[] theArray = new string[values.Length];

// loop through the 2-D System.Array and populate the 1-D String Array
 for (int i = 1; i <= values.Length; i++)
  {
   if (values.GetValue(1, i) == null)
    theArray[i-1] = "";
  else
   theArray[i-1] = (string)values.GetValue(1, i).ToString();
  }

  return theArray;
}
like image 75
Phani Kumar PV Avatar answered Oct 19 '22 23:10

Phani Kumar PV