在VSTO C#中获取Excel范围内最后一个非空单元格,可以通过以下几种方法实现
1、使用End方法(类似Excel快捷键Ctrl+方向键):
Excel.Range lastCell = worksheet.Range["A1"].End(Excel.XlDirection.xlDown);
2、遍历单元格方法(适用于不连续数据):
Excel.Range lastCell = null; foreach (Excel.Range cell in worksheet.Range["A1:A100"]) { if (!string.IsNullOrEmpty(cell.Text.ToString())) { lastCell = cell; } }
3、使用SpecialCells方法(性能较好):
Excel.Range lastCell = worksheet.Range["A:A"].SpecialCells( Excel.XlCellType.xlCellTypeConstants, Excel.XlSpecialCellsValue.xlTextValues).Areas.Last();
4、Find方法(最可靠的方式):
Excel.Range lastCell = worksheet.Range["A:A"].Find( "*", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlPrevious, false, Type.Missing, Type.Missing);
5、数组公式法(通过C#执行Excel公式):
string formula = "=LOOKUP(2,1/(A:A<>\"\"),A:A)"; Excel.Range lastCell = worksheet.Evaluate(formula) as Excel.Range;
注意事项:
- 方法4(Find方法)是最可靠的解决方案68
- 对于整列范围建议使用"A:A"格式5
- 处理前应检查Worksheet是否为空5
- 性能考虑:大数据量时Find方法最优