Search code examples
c#entity-frameworkopenxml-sdk

Convert from IEnumerable to String with OpenXML


I want to get the values from the second column of an excel using OpenXML to Read it. What I save in my DB is this

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[DocumentFormat.OpenXml.Spreadsheet.Cell,System.String]

But that column is a string. I use Entity Framework to insert in my table

foreach (Row r in sheet.Elements<Row>().Skip(1))
{
    db.Table.Add(new Table{
        Id= Convert.ToInt32(r.Elements<Cell>().First().CellValue.Text),
     Name= r.Elements<Cell>().Where(c=>c.CellReference=="B2").Select(x=>x.CellValue.Text).ToString()
    });
   db.SaveChanges();
}

Name is my second column.


Solution

  • This line:

    Name= r.Elements<Cell>().Where(c=>c.CellReference=="B2").Select(x=>x.CellValue.Text).ToString();
    

    Is causing the issue. Perhaps you want this:

    Name= r.Elements<Cell>().Where(c=>c.CellReference=="B2").Select(x=>x.CellValue.Text).SingleOrDefault().ToString();
                                                                                         ^^^^^^^^^^^^^