根据一列读取excel数据并提交给java类

我目前从Excel工作表中抽取我的数据,并使用testNG的dataProvider注释传递给我的testing。 我从Excel中返回数据的代码如下。

public static Object [][] excelData(String filepath) throws Exception { File excelFilePath = new File (filepath); FileInputStream fis = new FileInputStream(excelFilePath); HSSFWorkbook wb = new HSSFWorkbook(fis); HSSFSheet ws = wb.getSheet("Data"); int rowNum = ws.getLastRowNum()+1; int colNum = ws.getRow(0).getLastCellNum(); Object[][] data = new Object[rowNum][colNum]; for (int i=0; i<rowNum; i++){ HSSFRow row = ws.getRow(i); for (int j=0; j<colNum; j++){ HSSFCell cell = row.getCell(j); Object value =(Object) cellToString(cell); data[i][j] = (Object)value; // System.out.println("The value is " + value); } } System.out.println(Arrays.deepToString(data)); return data; } 

 public static Object cellToString(HSSFCell cell){ int type; Object result; type = cell.getCellType(); switch(type) { case 0://numeric value in excel result = cell.getNumericCellValue(); break; case 1: //string value in excel result = cell.getStringCellValue(); break; case 2: //boolean value in excel result = cell.getBooleanCellValue (); break; default: throw new RuntimeException("There are not support for type with id ["+type+"] of cell"); } return result; } 

目前的excel看起来像下面

实际的Excel

我需要根据最后一列传递用户名和密码

预计卓越

您的代码当前读取所有单元格。

在Excel文件中可能有不同大小的列。 如果仅获得第一行的大小,则将丢失行的某些单元格值(大于第一行的coulmn大小)。 而不是int colNum = ws.getRow(0).getLastCellNum(); 你应该写下你自己的方法来find最大的列大小。 调用这个方法int colNum = getMaxColumnNum(ws);

 public static int getMaxColumnNum(HSSFSheet ws) { int rowNum = ws.getLastRowNum() + 1; int max = 0; int temp = 0; for (int i = 0; i < rowNum; i++) { temp = ws.getRow(i).getLastCellNum(); if (max < temp) max = temp; } return max; } 

另外你的方法名是cellToString()但是它返回Object,你应该改变它的名字getCellValue()