/**
*
*/
/**
* @author WBY
*
*/
package com;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.visualizers.Sample;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ReadExcelSampler extends AbstractSampler {
private static final long serialVersionUID = 1L;
public final static String FUNCTION = "function";
public final static String sampName = "ReadExcelSampler∏";
private static final String String = null;
private int count =1;
JMeterVariables varp = null;
JMeterContext context = null;
@Override
public SampleResult sample(Entry entry) {
SampleResult result = new SampleResult();
//请求数据
//String requestData ="湖南";
result.setSampleLabel(sampName);
//result.setSamplerData(requestData);
result.setDataEncoding("UTF-8");
result.setDataType("text");
result.sampleStart();
varp = new JMeterVariables();
context = JMeterContextService.getContext();
//System.out.println(this.getProperty(FUNCTION));//输出GUI界面所输入的函数方法返回结果
varp = context.getVariables();
//context.setVariables(varp);
//varp.put("myname", requestData);
try {
String path = readPath().trim();
readExcel(path);
} catch (IOException e1) {
e1.printStackTrace();
}
result.sampleEnd();
result.setSuccessful(true);
return result;
}
/*-----------------读取Excel-------------------------------------*/
public void readExcel(String path) {
ReadExcelSamplerGUI readExcel = new ReadExcelSamplerGUI();
System.out.println("*** this.readExcel Path:"+path+" ***");
Workbook rwb = null;
try {
InputStream is = new FileInputStream(path);
rwb = Workbook.getWorkbook(is);
is.close();
// 这里有两种方法获取sheet表:名字和下标(从0开始)
// Sheet st = rwb.getSheet("original");
// 获取第一张Sheet表
int sheetNum = readExcel.getFunctionTextField().getSelectedIndex();
System.out.println("*** this.sheetNum:"+sheetNum+" ***");
Sheet rst = rwb.getSheet(sheetNum);
// 获取Sheet表中所包含的总列数
int rsColumns = rst.getColumns();
// 获取Sheet表中所包含的总行数
int rsRows = rst.getRows();
// 获取指定单元格的对象引用
Cell cell = null;
List list = new ArrayList();
//TreeMap map=new TreeMap();
rsRows = this.count += 1;//${__counter(false,test)}
System.out.println("*** this.count :"+this.count+" ***");
String str = "";
for (int i = 0; i < rsRows; i++)// rsRows
{
for (int j = 0; j < rsColumns; j++) {
// 引用方法:第一个变量为${Excel中的第一行的第一个字段}以此类推。
// 读取的数据行,第一行为变量名,第二行及以后为变量值。
cell = rst.getCell(j, i);
if (i == 0) {
list.add(cell.getContents());
System.out.println(cell.getContents());
continue;
}
varp.putObject(list.get(j).toString(), cell.getContents());
System.out.println(list.get(j) + " , " + cell.getContents());
}
}
} catch (Exception e) {
rwb.close();
System.out.println(e);
}
}
private static String readPath() throws IOException {
StringBuilder result = new StringBuilder();
FileReader fr = new FileReader("./tmp");
BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line = bufr.readLine()) != null){
bufr.read();
//System.out.println("line: "+line);
result.append(System.lineSeparator()+line);
}
bufr.close();
return result.toString();
}
}
package com;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.BeanShellInterpreter;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/*
* @author WANGBENYAN 微信: wby-wx 邮箱: [email protected]
*/
public class ReadExcelSamplerGUI extends AbstractSamplerGui {
private static final long serialVersionUID = 1L;
private JComboBox functionTextField = null;
private JTextField UploadText = null;
private JTable table = null;
private JTextArea copyNameText = null;
private JTextField startColTest = null;
private JTextField startRowText = null;
private Object[][] data = {};
private String[] columnNames = {};
private DefaultTableModel model = null;
private boolean DEBUG = true;
public ReadExcelSamplerGUI() {
init();
}
@Override
public void configure(TestElement element) {
//配置组装元素信息,BeanSheel 中调用print( props.get("FUNCTION"));
super.configure(element);
functionTextField.addItem(element.getPropertyAsString(ReadExcelSampler.FUNCTION));
}
private void init() {
// GridBagLayout 网格布局;容器的空间划分成M×N列的网格区域, 每个区域只能放置一个组件。
// 边界布局 ;容器划分为东、西、南、北、中五个区域,每个区域只能放置一个组件。
// BorderLayout 边界布局管理器,
// setBackground(Color.lightGray);
setLayout(new BorderLayout(15, 15));// 组件间横向、纵向间距均为15像素
JLabel title = new JLabel(" Excel读取测试用例");
title.setFont(new Font("微软雅黑", 1, 14));
// add("North", new JButton("North"));
add("North", title);
setLayout(null);
title.setBounds(10, 30, 200, 20);
setLayout(new BorderLayout(15, 15));
// title.setBackground(Color.green);
JLabel content = new JLabel("※ 注:读取所有用例,并设置为全局变量,调用变量直接使用 : {用例字段} ");
content.setForeground(Color.RED);
content.setFont(new Font("微软雅黑", 1, 12));
content.setBounds(10, 60, 600, 20);// x,y,width,height
add(content);
JLabel path = new JLabel("文件路径:");
path.setBounds(10, 95, 75, 22);
path.setFont(new Font("微软雅黑", 1, 12));
add(path);
// JTextField UploadText = new JTextField();
UploadText = new JTextField();
UploadText.setBounds(72, 95, 500, 22);
add(UploadText);
JButton UploadButton = new JButton(" 浏览 ");
UploadButton.setFont(new Font("微软雅黑", 1, 12));
UploadButton.setBounds(575, 95, 70, 20);
add(UploadButton);
// ---------------------------------- 文件上传功能
UploadButton.addMouseListener(new MouseAdapter() { // 添加鼠标点击事件
public void mouseClicked(MouseEvent event) {
excelImport();
}
});
JLabel sheet = new JLabel("Sheet 索引序号:");
sheet.setBounds(10, 135, 180, 22);
sheet.setFont(new Font("微软雅黑", 1, 12));
add(sheet);
// JTextField sheetcount = new JTextField();
functionTextField = new JComboBox();
functionTextField.setBounds(120, 135, 100, 22);
functionTextField.addItem(0);
add(functionTextField);
JLabel startRow = new JLabel("开始行:");
startRow.setBounds(230, 135, 80, 22);
startRow.setFont(new Font("微软雅黑", 1, 12));
add(startRow);
startRowText = new JTextField();
startRowText.setBounds(282, 135, 100, 22);
startRowText.setText("1");
add(startRowText);
JLabel startCol = new JLabel("结束行:");
startCol.setBounds(390, 135, 100, 22);
startCol.setFont(new Font("微软雅黑", 1, 12));
add(startCol);
startColTest = new JTextField();
startColTest.setBounds(442, 135, 100, 22);
startColTest.setText("1000");//默认读取1000条
add(startColTest);
/* JButton saveconfig = new JButton("保存配置");
saveconfig.setBounds(555, 135, 90, 20);
saveconfig.setFont(new Font("微软雅黑", 1, 12));
add(saveconfig);*/
/*---------------输出变量名--------------------*/
JLabel copyName = new JLabel("输出变量名(copy):");
copyName.setBounds(10, 170, 200, 22);
copyName.setFont(new Font("微软雅黑", 1, 12));
add(copyName);
copyNameText = new JTextArea(3, 20);
copyNameText.setLineWrap(true);// 激活自动换行功能
copyNameText.setWrapStyleWord(true);// 激活断行不断字功能
copyNameText.setBackground(Color.white);
copyNameText.setBounds(10, 200, 650, 100);
copyNameText.setFont(new Font("微软雅黑", 4, 15));
copyNameText.setForeground(Color.blue);
add(copyNameText);
JPanel copyNamePanel = new JPanel();
copyNamePanel.setLayout(null);
copyNamePanel.setBounds(10, 200, 1000, 100);
// copyNamePanel.setBackground(Color.red);
copyNamePanel.add(copyNameText);
JScrollPane jscrollPane = new JScrollPane(copyNameText);
jscrollPane.setBounds(10, 200, 650, 100);
copyNamePanel.add(jscrollPane);
jscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(jscrollPane, BorderLayout.CENTER);
/*-----------------TestCase---------------*/
JLabel casedata = new JLabel("数据详情:");
casedata.setBounds(10, 350, 200, 22);
casedata.setFont(new Font("微软雅黑", 1, 12));
add(casedata);
JButton lookData = new JButton("查看测试结果");
lookData.setBounds(550, 350, 110, 20);
lookData.setFont(new Font("微软雅黑", 1, 12));
add(lookData);
// ---------------------------------- 打开Excel文件
lookData.addMouseListener(new MouseAdapter() { // 添加鼠标点击事件
public void mouseClicked(MouseEvent event) {
if(UploadText.getText().equals("")){
JOptionPane.showMessageDialog(null,"文件路径不能为空!", "系统提示!", JOptionPane.ERROR_MESSAGE);
}else{
openExcelFile(UploadText.getText());
}
}
});
columnNames = new String[] {};
// 创建显示数据
data = new Object[][] {};
model = new DefaultTableModel(data, columnNames);
/*
* JTable还提供了一个重载的构造方法,传入两个Vector JTable(Vector rowData, Vector columnNames)
*/
table = new JTable(model);
DefaultTableCellRenderer r = new DefaultTableCellRenderer();
r.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Object.class, r);
table.getTableHeader().setFont(new Font("微软雅黑", 1, 13));
// table.setFont(new Font("微软雅黑", 1, 12));
table.setPreferredScrollableViewportSize(new Dimension(1000, 800));
table.setBackground(Color.yellow);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
// 这也是官方建议使用的方式,否则表头不会显示,需要单独获取到TableHeader自己手动地添加显示
JPanel centerPanel = new JPanel();
centerPanel.setLayout(null);
centerPanel.setBounds(10, 380, 1100, 810);
// Container contTable = frame.getContentPane();
centerPanel.add(table);
setLayout(new BorderLayout());
// 创建包含表格的滚动窗格
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(10, 380, 1100, 200);
centerPanel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// 定义 topPanel 的布局为 BoxLayout,BoxLayout 为垂直排列
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
// 先加入一个不可见的 Strut,从而使 topPanel 对顶部留出一定的空间
centerPanel.add(Box.createVerticalStrut(190));
// 加入包含表格的滚动窗格
add(centerPanel);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setPreferredSize(new Dimension(100, 100));// 使用布局管理器 设置宽度
// mainPanel.setBackground(Color.pink);
// mainPanel.setBorder(BorderFactory.createTitledBorder("title"));
add(mainPanel);
}
/*-----------------读取Excel-------------------------------------*/
public void readExcel(String filePath) {
Workbook rwb = null;
try {
InputStream is = new FileInputStream(filePath);
rwb = Workbook.getWorkbook(is);
is.close();
// 这里有两种方法获取sheet表:名字和下标(从0开始)
// Sheet st = rwb.getSheet("original");
// 获取第一张Sheet表
int sheetNum = functionTextField.getSelectedIndex();
List li = new ArrayList();
functionTextField.removeAllItems();
for(int i =0;i endcount){
model.getDataVector().removeElementAt(1);
}
}
System.out.println(model.getDataVector().toString());
rwb.close();
} catch (Exception e) {
System.out.println(e);
}
}
private void printDebugData(JTable table) {// 打印table 数据
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("TestCase data: ");
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("----------------------------------------------");
}
/**
* 文件上传功能
*
* @param developer
* 按钮控件名称
*/
public void excelImport() {
JFileChooser chooser = new JFileChooser(new File("D:\\"));//选择器的初始目录定为d盘
chooser.setMultiSelectionEnabled(true);
/** 过滤文件类型 * *//** "Execl files(*.xls|*.xlsx)", "xls", "xlsx" **/
FileNameExtensionFilter filter = new FileNameExtensionFilter("Execl files(*.xls)", "xls");
chooser.setFileFilter(filter);
chooser.showOpenDialog(null);
try {
UploadText.setText(chooser.getSelectedFile().toString());
System.out.println("选择的文件路径为:" + chooser.getSelectedFile().toString());
readExcel(UploadText.getText());
writePath();
} catch (Exception e) {
System.out.println("上传文件出错啦...");
}
}
private void writePath() throws IOException {
File fl = new File("./tmp");
FileWriter fileWritter = new FileWriter(fl.getName(),false);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
//System.out.println("*** write Path :"+UploadText.getText());
bufferWritter.write(UploadText.getText());
bufferWritter.flush();
bufferWritter.close();
}
public void openExcelFile(String filePath) {
try {
System.out.println("\nstart Open Excel file ._. ");
Runtime.getRuntime().exec("cmd /c start "+filePath);
} catch (IOException e) {
System.out.println("打开文件异常: "+e);
}
}
@Override
public TestElement createTestElement() {// 创建所对应的Sampler
//创建新的元素
TestElement sampler = new ReadExcelSampler();
modifyTestElement(sampler);
return sampler;
}
@Override
public String getLabelResource() {
// label信息,也就是创建HTTP请求、JAVA请求
return this.getClass().getSimpleName();
}
@Override
public void modifyTestElement(TestElement sampler) {
// 清除旧的组件,从新创建
super.configureTestElement(sampler);
if (sampler instanceof ReadExcelSampler) {
ReadExcelSampler testSmpler = (ReadExcelSampler) sampler;
testSmpler.setProperty(ReadExcelSampler.FUNCTION, functionTextField.getSelectedIndex());
}
}
@Override
public String getStaticLabel() {// 设置显示名称
return "ReadExcelSampler∏";
}
private void initFields() {
//functionTextField.addItem("0");
}
@Override
public void clearGui() {
//清除页面数据信息
super.clearGui();
initFields();
}
public JComboBox getFunctionTextField() {
return functionTextField;
}
public void setFunctionTextField(JComboBox functionTextField) {
this.functionTextField = functionTextField;
}
public JTextField getUploadText() {
return UploadText;
}
public void setUploadText(JTextField uploadText) {
UploadText = uploadText;
}
public JTextField getStartColTest() {
return startColTest;
}
public void setStartColTest(JTextField startColTest) {
this.startColTest = startColTest;
}
public JTextField getStartRowText() {
return startRowText;
}
public void setStartRowText(JTextField startRowText) {
this.startRowText = startRowText;
}
}