I write a method to return Excel sheet cell value when pass filename , sheetname and cell address.
public static string GetCellValue(string fileName, string sheetName, string addressName)
{
string value = null;
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart wbPart = document.WorkbookPart;
Where(s => s.Name == sheetName).FirstOrDefault();
if (theSheet == null)
{
throw new ArgumentException("sheetName");
}
WorksheetPart wsPart =
(WorksheetPart)(wbPart.GetPartById(theSheet.Id));
Cell theCell = wsPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == addressName).FirstOrDefault();
if (theCell != null)
{
value = theCell.InnerText;
if (theCell.DataType != null)
{
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
.
var stringTable =
wbPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
default:
value = "TRUE";
break;
}
break;
}
}
}
}
return value;
}
here is how call the above method.
private void button1_Click(object sender, EventArgs e)
{
const string fileName = @"C:\Users\dkumarage\Desktop\Book1.xlsx";
string value = GetCellValue(fileName, "Sheet1", "A1");
textBox1.Text = value;
}
this way I can only gain 1 cell value. How can I call this method recursively to gain all cell values. please help me.
(here I can not pass a range. Because I dont know the range. Instead I have to use while(not end of rows))
thank you
I don’t know why you want it to be recursive. Anyway, here is a non recursive version of what you want to do. It uses Excel interop and I didn’t bother to manage exceptions (things like file not found, or worksheet non existent and so on), but it should give you a starting point.