How do I access a cell in Excel Interop when using

2019-09-15 05:25发布

I originally had a code segment that iterated through rows of an Excel spreadsheet using the UsedRange as such:

           range = ws.UsedRange;
           for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }

But I needed to only get the rows that remained after I applied a filter so (after viewing How can I get the Range of filtered rows using Excel Interop?) I changed the code as such:

    range = ws.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);
    foreach (Excel.Range area in range.Areas)
    {
        foreach (Excel.Range row in area.Rows)
            //for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }
    }

Except now I'm getting type mismatch errors. What fundamental thing am I missing here?

1条回答
乱世女痞
2楼-- · 2019-09-15 06:03

I believe you are getting a type mismatch at the call to ws.Cells[row, "N"]. In the original code, row is an int. In the modified code, row is an Excel.Range.

Given that, in the modified code, row is a single row (multiple column) range, all you should need to do is index into the cell in that row which corresponds to column N. Assuming your range starts in column A, this will be the cell in 14th column.

E.g.

Object nObj = ((Excel.Range)row.Cells[1, 14]).Text;
查看更多
登录 后发表回答