Jmeter-采用rt.jar和jxl.jar读取excel
将rt.jar和jxl.jar,放在\apache-jmeter-5.0\lib\ext下面
import java.io.*; import java.util.ArrayList; import java.util.List; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; String path = "C:/123.xls"; InputStream instream = new FileInputStream(path); Workbook readwb = null; Cell cell= null; readwb = Workbook.getWorkbook(instream); // 获取第一张Sheet表,Sheet的下标是从0开始 Sheet readsheet = readwb.getSheet(0); // 获取Sheet表中所包含的总列数 int rsColumns = readsheet.getColumns(); // 获取Sheet表中所包含的总行数 int rsRows = readsheet.getRows(); // 获取指定单元格的对象引用 List list = new ArrayList(); // 线程数(按线程数取行数) rsRows = ${__threadNum}; print("线程数=========== :"+${__threadNum}); for (int i = 0; i < rsRows; i++) //行 { for (int j = 0; j < rsColumns; j++) //列 { cell = readsheet.getCell(j,i); //list存第一行名字 if( i== 0){ list.add(cell.getContents()); #取值 continue; } //put变量存第二行以后的值(线程3以后会反复替换以前put的值) vars.put(list.get(j),cell.getContents()); print(vars.get(list.get(j))); } } //log.info("isEnc:"+vars.get("name"));//调用jmeter内置log对象,日志会打印到jmeter.log中 //System.out.println(vars.get(list.get(j)));//打印 //print(vars.get(list.get(j)));//打印 //return vars.get(list.get(j));//返回 //print((vars.get("表头"))
由于每个线程获取到该线程行的数据,都需要从前往后读取到该线程行,因而进行了大量的vars.put()替换值操作。
优化以上问题:只读取第一行和线程行,再存入vars.put()。
import java.io.*; import java.util.ArrayList; import java.util.List; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; String path = "C:/123.xls"; InputStream instream = new FileInputStream(path); Workbook readwb = null; Cell cell= null; readwb = Workbook.getWorkbook(instream); // 获取第一张Sheet表,Sheet的下标是从0开始 Sheet readsheet = readwb.getSheet(0); // 获取Sheet表中所包含的总列数 int rsColumns = readsheet.getColumns(); // 获取Sheet表中所包含的总行数 int rsRows = readsheet.getRows(); // 获取指定单元格的对象引用 List list = new ArrayList(); //线程数(按线程数取行数) rsRows = ${__threadNum}; //该线程只读第一行和应该读的最后一行 int[] myRows = {0,rsRows-1}; print("线程数=========== :"+${__threadNum}); for (int i = 0; i < myRows.length; i++) //行 { for (int j = 0; j < rsColumns; j++) //列 { cell = readsheet.getCell(j, myRows[i]); //list存第一行名字 if(myRows[i] == 0){ list.add(cell.getContents()); continue; } //put变量只存最后一行的值 vars.put(list.get(j),cell.getContents()); print(vars.get(list.get(j))); } }
其实以上两种都不影响最后需要的结果,只是影响效率
在接口传参时直接 ${"表头"}