如何使用ClosedXML从Excel文件中读取单元格值

时间:2018-08-10 16:31:32

标签: c# excel closedxml

        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);
            }
        }

我正在尝试使用ClosedXML从excel文件中读取。我找到的每个参考都说您可以使用Worksheet.Cell(r,c),但其中不包含.Cell的定义。 .Row都没有。我尝试过在ClosedXML下为所有内容包括“使用”语句,但这也不起作用。我想念什么?

给出的错误...'IEnumerable [IXLRangeRow]'不包含'Cell'的定义,并且找不到扩展方法'Cell'接受类型为'IEnumerable [IXLRangeRow]'的第一个参数(您是否缺少一个使用指令还是程序集引用?)

ws1.Cell和ws1.Row均出现错误

支持此目的的参考文献应该起作用... -Reading from Excel File using ClosedXML -https://github.com/closedxml/closedxml/wiki/Cell-Values

1 个答案:

答案 0 :(得分:2)

好的,找到了解决方案。谢谢@Crowcoder的指导...

        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();
            }
        }