简体   繁体   中英

Return cell with value not null using linq - Epplus

I'm using the Linq code below to return the last filled cell in my row. However, I do not know for what reason (maybe some formatting, or something of the sort) cell with null value is being returned. Example

My row starts at B16 and goes to AG16, the code in thesis should return AG16, but this is returning AI16, and this cell is blank, has no value, formula, nothing.

I would like to ignore cells with the Blank Value, so to return AG16.

I'm doing according to the code below, which returns AI16 even though it has no value

var lastRowCellValue = worksheet.Cells.Last(c => c.End.Row == 16)
  • 16 is the line row that he will check

I have already tried to use the code below, but it returns NULL instead of AG16, which is my last value cell

 var lastRowCellValue = worksheet.Cells.Last(c => c.End.Row == 16).Where(c => c.Value != null);

What am I doing wrong?

Assuming that the issue is similar to this , with empty cells or formatting causing the problem, you could use a function derived from this answer :

int LastColumnByRow(ExcelWorksheet sheet, int rownum) {
    var col = sheet.Dimension.End.Column;

    while (col >= 1) {
        if (!string.IsNullOrEmpty(sheet.Cells[rownum, col].Text)) {
            break;
        }
        col--;
    }
    return col;
}

Called like so:

var lastRowCellValue = worksheet.Cells[16, LastColumnByRow(ws, 16)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM