1 import java.io.File; 2 import java.io.IOException; 3 import org.testng.annotations.DataProvider; 4 import org.testng.annotations.Test; 5 import jxl.Cell; 6 import jxl.Sheet; 7 import jxl.Workbook; 8 /** 9 * 读取execl文件 10 */ 11 public class File_excel { 12 13 // 测试案例绑定DataProvider后自动循环执行 14 @Test(dataProvider = "getData") 15 public void testSearch(String p1, String p2) { 16 System.out.println(p1 + " " + p2); 17 } 18 19 public static Object[][] readData(String dataFile, String sheetName, int beginRowNum, int rowOffset, 20 int beginColumnNum, int columnOffset) { 21 return read(dataFile, sheetName, beginRowNum, rowOffset, beginColumnNum, columnOffset); 22 } 23 24 // 定义数据驱动 25 @DataProvider(name = "getData") 26 public static Object[][] getData() throws IOException { 27 return readData("H:\test.xls", "sheet1", 0, 0, 0, 0); 28 } 29 30 /** 31 * @param dataFile 32 * 文件名 33 * @param sheetName 34 * excel中的sheet 35 * @param beginRowNum 36 * 开始行 37 * @param rowOffset 38 * 行偏移量 39 * @param beginColumnNum 40 * 开始列 41 * @param columnOffset 42 * 列偏移量 43 * @return 44 */ 45 private static Object[][] read(String dataFile, String sheetName, int beginRowNum, int rowOffset, 46 int beginColumnNum, int columnOffset) { 47 File excelFile = new File(dataFile); 48 Workbook wb = null; 49 Object[][] data = null; 50 try { 51 wb = Workbook.getWorkbook(excelFile); 52 Sheet sheet = wb.getSheet(sheetName); 53 if (sheet == null) 54 return null; 55 int rows = sheet.getRows(); 56 int cols = sheet.getColumns(); 57 if (rowOffset == 0) { 58 rowOffset = rows - beginRowNum; 59 } else if (rows < (beginRowNum + rowOffset)) { 60 rowOffset = rows - beginRowNum; 61 } 62 if (columnOffset == 0) { 63 columnOffset = cols - beginColumnNum; 64 } else if (cols < (beginColumnNum + columnOffset)) { 65 columnOffset = cols - beginColumnNum; 66 } 67 data = new Object[rowOffset][columnOffset]; 68 for (int i = beginRowNum; i < beginRowNum + rowOffset; i++) { 69 for (int j = beginColumnNum; j < beginColumnNum + columnOffset; j++) { 70 // 获取单元格数据 getCell(col,row); 71 Cell cell = sheet.getCell(j, i); 72 if (cell != null) { 73 String celldata = cell.getContents().trim(); 74 data[i - beginRowNum][j - beginColumnNum] = celldata; 75 } 76 } 77 } 78 } catch (Exception e) { 79 throw new RuntimeException(e); 80 } 81 return data; 82 } 83 }
test.xls文件内容: