首先定义扩展方法:
1 public static ICell GetCell(this IRow row, string clounmName) 2 { 3 IRow firstRow = row.Sheet.GetRow(0); 4 for (int i = 0; i < firstRow.PhysicalNumberOfCells; i++) 5 { 6 if (firstRow.GetCell(i).GetValue() == clounmName) 7 { 8 return row.GetCell(i); 9 } 10 } 11 throw new Exception(string.Format("未找到名为\"{0}\"的列头", clounmName)); 12 }
调用:
FileStream fs = new FileStream(fileName, FileMode.Open) IWorkBook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs); string value = string.Empty; ISheet sheet = workbook.GetSheetAt(0);
for (int i = 1; i < sheet.PhysicalNumberOfRows; i++) { value = sheet.GetRow(i).GetCell("数量").GetValue(); }
附:扩展方法的使用:
扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
1 //创建自己的静态类 2 public static class MyExtension 3 { 4 //静态方法 5 public static int Number(this String str) 6 { 7 return str.Length; 8 } 9 }
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //使用扩展方法 6 string str = "Hello World"; 7 Console.WriteLine(str.Number()); 8 } 9 }