问题
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:
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;
来源:https://stackoverflow.com/questions/8467167/how-do-i-access-a-cell-in-excel-interop-when-using-filtered-ranges