Home » excel » c# – How to read cell value from excel file using ClosedXML

c# – How to read cell value from excel file using ClosedXML

Posted by: admin May 14, 2020 Leave a comment

Questions:
        string TablePath = Storage.ProjectPath + "\Tables\";
        string ObjectRepPath = TablePath + "ObjectRepository.xlsx";

        string locType = " ";
        string locParm = " ";

        var workbook  = new XLWorkbook(ObjectRepPath);
        var ws1       = workbook.Worksheet(1).RangeUsed().RowsUsed().Skip(1);
        var totalRows = ws1.Count();
        var row       = ws1.Row;

        for (int rCnt = 1; rCnt <= totalRows; rCnt++)
        {
            var objPage    = ws1.Cell(rCnt, 0).Value;
            var objElement = ws1.Cell(rCnt, 1).Value;


            if (objPage == page && objElement == element)
            {
                locType = ws1.Cell(rCnt, 2);
                locParm = ws1.Cell(rCnt, 3);
            }
        }

I’m attempting to use ClosedXML to read from an excel file. Every reference I’ve found says you can use Worksheet.Cell(r,c), but it doesn’t contain a definition for .Cell. Neither is there one for .Row. I’ve tried including ‘using’ statements for everything under ClosedXML, but that didn’t work either. What am I missing?

Error given … ‘IEnumerable[IXLRangeRow]’ does not contain a definition for ‘Cell’ and no extension method ‘Cell’ accepting a first argument of type ‘IEnumerable[IXLRangeRow]’ could be found (are you missing a using directive or an assembly reference?)

Error on both ws1.Cell and ws1.Row

References that support this should work …
Reading from Excel File using ClosedXML
https://github.com/closedxml/closedxml/wiki/Cell-Values

How to&Answers:

Okay, found a solution. Thank you to @Crowcoder for the guidance…

        var workbook = new XLWorkbook(ObjectRepPath);
        var rows     = workbook.Worksheet(1).RangeUsed().RowsUsed().Skip(1);

        foreach (var row in rows)
        {
            var rowNumber  = row.RowNumber();

                objPage    = row.Cell(1).GetString();
                objElement = row.Cell(2).GetString();

            if (objPage == page && objElement == element)
            {
                locType = row.Cell(3).GetString();
                locParm = row.Cell(4).GetString();
            }
        }