我正在尝试阅读Excel表
添加了所需的Jars
.classpath中添加的poi jar在下面
<classpathentry kind="lib" path="External_Jars/poi/commons-codec-1.10.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/commons-logging-1.2.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/curvesapi-1.03.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/jsqlparser-0.8.0.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/poi-3.14-20160307.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/poi-excelant-3.14-20160307.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/poi-ooxml-3.14-20160307.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/poi-ooxml-schemas-3.14-20160307.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/poi-scratchpad-3.14-20160307.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/sqlsheet-6.5.jar"/>
<classpathentry kind="lib" path="External_Jars/poi/xmlbeans-2.6.0.jar"/>
例外是-
java.lang.IllegalArgumentException: Cell index must be >= 0
at org.apache.poi.xssf.usermodel.XSSFRow.getCell(XSSFRow.java:237)
at org.apache.poi.xssf.usermodel.XSSFRow.getCell(XSSFRow.java:224)
at org.apache.poi.xssf.usermodel.XSSFRow.getCell(XSSFRow.java:44)
at com.hp.commercial.framework.common.JDBCExcel.updateTestCaseDoc(JDBCExcel.java:546)
at com.hp.commercial.framework.common.WebDriverListener1.afterInvocation(WebDriverListener1.java:262)
at org.testng.internal.invokers.InvokedMethodListenerInvoker$InvokeAfterInvocationWithoutContextStrategy.callMethod(InvokedMethodListenerInvoker.java:100)
at org.testng.internal.invokers.InvokedMethodListenerInvoker.invokeListener(InvokedMethodListenerInvoker.java:62)
at org.testng.internal.Invoker.runInvokedMethodListeners(Invoker.java:566)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:713)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
阅读Excel工作表代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.remote.RemoteWebDriver;
public class JDBCExcel{
private Connection con = null;
private ResultSet resultSet = null;
private Statement st = null;
private Workbook workBook = null;
private FileInputStream fileInputStream = null;
private String filePath = null;
/**
* WritingExcel method will be used with inline calling from method where
* needed to update excel sheet after updating by POI.
* @throws SQLException
*/
private void WritingExcel() throws SQLException {
try {
// closing connectiona and fileinput Stream for already oepened excel file
this.connectionClose();
// creating fileoutput Stream and writing
FileOutputStream fileOutput = new FileOutputStream(new File(filePath));
workBook.write(fileOutput);
// closing fileoutput Steram
fileOutput.close();
// Reloading excel file using fileinput Stream
this.loadExcel(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* load excel file from path. Based on its extension .xls or .xlsx, workbook
* using POI As well, formal declaration to get connection for driver
* manager using SqlSheet API
*
* @param path
*
*/
public void loadExcel(String path) {
try {
filePath = path;
fileInputStream = new FileInputStream(new File(filePath));
// check extension of file to determine workbook type
String fileExt = path.substring(path.indexOf(".")).toLowerCase();
// create workbook class based on file extension
if (fileExt.equals(".xls"))
workBook = new HSSFWorkbook(fileInputStream);
else if (fileExt.equals(".xlsx"))
workBook = new XSSFWorkbook(fileInputStream)
} catch (Throwable e) {
e.printStackTrace();
}
}
/**
* getRowId method to get particular row idneified by id value in ID column
* in Last-to-First manner. This will be handled by SqlSheet API
*
* @param sheet
* @param id
* @return
* @throws SQLException
*/
public Map<String, String> getRowbyID(String sheet, String id)
throws SQLException {
Map<String, String> map = new HashMap<>();
// TO DO.. how to execute Where in SQL Query in JAVA 8
String strQuery = "SELECT * FROM " + this.getSheetFormat(sheet); // + " WHERE ID= '" + id +
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
ResultSetMetaData rmd = resultSet.getMetaData();
while (resultSet.next()) {
//drawback to read cell again..so this is used.
String idCell = resultSet.getString("ID");
// Temporary solution until Where clause working in SQL Query
if (id.equalsIgnoreCase(idCell)) {
int columntCount = rmd.getColumnCount();
map.put(rmd.getColumnName(1), idCell);
for (int i = 2; i <= columntCount; i++) {
map.put(rmd.getColumnName(i), resultSet.getString(i));
}
break;
}
}
resultSet.close();
return map;
}
public String getValuebyParamName(String sheet, String paramName)
throws SQLException {
String strParamValue = "";
// TO DO.. how to execute Where in SQL Query in JAVA 8
String strQuery = "SELECT * FROM " + this.getSheetFormat(sheet); // + " where ParamName = " + paramName;
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
while (resultSet.next()) {
// Temporary solution until Where clause working in SQL Query
if (paramName.equalsIgnoreCase(resultSet.getString("ParamName"))) {
strParamValue = resultSet.getString("ParamValue");
strParamValue = (strParamValue == null) ? "" : strParamValue;
break;
}
}
resultSet.close();
return strParamValue;
}
public String getValueByAnyColumn(String sheet, String refColumn, String refKey, String targetCol)
throws SQLException {
String strValue = "";
String strQuery = "SELECT * FROM " + this.getSheetFormat(sheet);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
while (resultSet.next()) {
if (refKey.equalsIgnoreCase(resultSet.getString(refColumn))) {
strValue = resultSet.getString(targetCol);
strValue = (strValue.equalsIgnoreCase("$Null")) ? "" : strValue;
break;
}
}
resultSet.close();
return strValue;
}
public String getNextValueOfColumn(String sheet, String column, String refKey) throws SQLException {
String strValue = "";
String strQuery = "SELECT * FROM " + this.getSheetFormat(sheet);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
resultSet.last();
int resultSize = resultSet.getRow();
resultSet.beforeFirst();
while (resultSet.next()) {
if (refKey.equals(resultSet.getString(column))) {
if ((resultSize) == resultSet.getRow()) {
resultSet.first();
strValue = resultSet.getString(column);
strValue = (strValue.equalsIgnoreCase("$Null")) ? "" : strValue;
} else {
resultSet.next();
strValue = resultSet.getString(column);
strValue = (strValue.equalsIgnoreCase("$Null")) ? "" : strValue;
}
break;
}
}
resultSet.close();
return strValue;
}
public void updateParticularColumnValue(String sheetNm, String columnNm, String targetValue, String replaceValue, String... ParamName) throws Exception{
// Declaring Variables
String paramName = ParamName.length > 0 ? ParamName[0]: "";
Iterator<Row> rows = null;
ArrayList<String> columnNames = new ArrayList<String>();
// Opening spreadsheet
Sheet sheetName = workBook.getSheet(sheetNm);
// Collecting row Iterator
rows = sheetName.rowIterator();
// Reading first row of excel as column Titles
if (rows.hasNext()) { columnNames = this.getAllColumnTitles(rows.next().cellIterator()); }
boolean isForSingleRow = !paramName.isEmpty();
// Reading rest of rows as column values
while (rows.hasNext()) {
// getting next row
Row row = rows.next();
if(isForSingleRow) {
// not updating single row
break;
}
else {
if (row.getCell(columnNames.indexOf(columnNm.toLowerCase())).getStringCellValue().equalsIgnoreCase(targetValue)) {
//Else update each row turn by turn in loop
row.getCell(columnNames.indexOf(columnNm.toLowerCase())).setCellValue(replaceValue);
if (rows.hasNext()) {
row = rows.next();
row.getCell(columnNames.indexOf(columnNm.toLowerCase())).setCellValue(targetValue);
} else {
if (DriverScript.executionMode.equalsIgnoreCase("ITG")) {
CommonUtils.getExcel(Excel.Files.User).updateParticularColumnValue(Excel.User.Password.name(), "ITGStatus", "Old", "New");
} else {
CommonUtils.getExcel(Excel.Files.User).updateParticularColumnValue(Excel.User.Password.name(), "Status", "Old", "New");
}
}
break;
}
}
}
WritingExcel();
}
public List<ExecutionConfig> getModules() throws SQLException {
List<ExecutionConfig> listReturn = new ArrayList<ExecutionConfig>();
String Product = DriverScript.product;
String ProductExecutionconfig = Product + "ExecutionConfig";
// TO DO.. how to execute Where in SQL Query in JAVA 8
String strQuery = "SELECT * FROM " + this.getSheetFormat(ProductExecutionconfig); // +
// " WHERE SelectedToExecute='Yes' and Executed='No'";
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
Map<ExecutionConfig, Integer>unsortedExecutionConfigMap = new LinkedHashMap<>();
while (resultSet.next()) {
// Temporary solution until Where clause working in SQL Query
if ("Yes".equalsIgnoreCase(resultSet.getString("SelectedToExecute"))
&& "No".equalsIgnoreCase(resultSet.getString("Executed"))) {
ExecutionConfig obj = new ExecutionConfig(
resultSet.getString("ModuleName"),
resultSet.getString("TestCategory"),
resultSet.getString("RiskLevel"),
0); //No priority as it is decided in next block
unsortedExecutionConfigMap.put(obj, Integer.valueOf(resultSet.getString("ExecutionPriority").isEmpty() ? "0" : resultSet.getString("ExecutionPriority")));
}
}
resultSet.close();
Integer[] uniquePriorityNumbers = unsortedExecutionConfigMap.values().stream().sorted().distinct().toArray(Integer[]::new);
for(int currentPriority : uniquePriorityNumbers){
unsortedExecutionConfigMap.entrySet().forEach(e ->
{
if(e.getValue() == currentPriority){
ExecutionConfig eObj = e.getKey();
eObj.setModulePriority(listReturn.size());
listReturn.add(eObj);
}
});
}
return listReturn;
}
public List<TestCases> getActionList(ExecutionConfig selectedConfig)
throws SQLException {
String strModule = selectedConfig.strModuleName;
String strTestCategory = selectedConfig.strTestCat;
String strRiskLevel = selectedConfig.strRiskLevel;
List<TestCases> listReturn = new ArrayList<TestCases>();
// TO DO.. how to execute Where in SQL Query in JAVA 8
String strQuery = "SELECT * FROM " + this.getSheetFormat(strModule);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
while (resultSet.next()) {
String testCategory = resultSet.getString("TestCategory");
String riskLevel = resultSet.getString("RiskLevel");
if ("1".equalsIgnoreCase(String.valueOf(resultSet.getInt("Enabled"))) && "Automated".equalsIgnoreCase(resultSet.getString("TestExecution")) && strTestCategory.equalsIgnoreCase(testCategory) && strRiskLevel.equalsIgnoreCase(riskLevel)) {
TestCases obj = new TestCases(resultSet.getString("TCID"),
resultSet.getString("Action"),
testCategory,
riskLevel,
resultSet.getString("TestDescription"));
listReturn.add(obj);
}
}
resultSet.close();
return listReturn;
}
public void updateExecutionConfig(String strModuleName,
String strTestCategory) throws SQLException, IOException {
// Declaring Variables
String Product = getValuebyParamName(DriverScript.prodConfigSheetName,
"Product");
String ProductExecutionconfig = Product + "ExecutionConfig";
Iterator<Row> rows = null;
ArrayList<String> columnNames = new ArrayList<String>();
int updateRow = 0;
// Opening spreadsheet
Sheet sheetName = workBook.getSheet(ProductExecutionconfig);
// Collecting row Iterator
rows = sheetName.rowIterator();
// Reading first row of excel as column Titles
if (rows.hasNext()) {
columnNames = this.getAllColumnTitles(rows.next().cellIterator());
}
// Reading rest of rows as column values
while (rows.hasNext()) {
// getting next row
Row row = rows.next();
// converting cell type to String type to read cell value as string
row.getCell(columnNames.indexOf("modulename")).setCellType(
Cell.CELL_TYPE_STRING);
row.getCell(columnNames.indexOf("testcategory")).setCellType(
Cell.CELL_TYPE_STRING);
if ((String.valueOf(row.getCell(columnNames.indexOf("modulename")))
.equalsIgnoreCase(strModuleName))
&& (String.valueOf(row.getCell(columnNames
.indexOf("testcategory")))
.equalsIgnoreCase(strTestCategory))) {
{
// updating row
row.getCell(columnNames.indexOf("executed")).setCellValue(
"Yes");
updateRow++;
}
}
}
LocalLogManager.logf.info(Product + "ExecutionConfig for Module "
+ strModuleName + " has been updated for rows " + updateRow);
WritingExcel();
}
public void connectionClose() throws SQLException, IOException {
if (con != null){
con.close();
fileInputStream.close();}
}
public Connection getCon() {
return con;
}
public Statement getSt() {
return st;
}
public void closeStmt() throws SQLException {
if (st != null)
st.close();
}
public void updateTestCaseDoc(String sModuleName, String sActionName,
String sStatus) throws SQLException, ClassNotFoundException {
// Declaring Variables
Iterator<Row> rows = null;
ArrayList<String> columnNames = new ArrayList<String>();
String BrowserName = ((RemoteWebDriver)LocalDriverFactory.getDriver()).getCapabilities().getBrowserName();
BrowserName = BrowserName.equalsIgnoreCase("Internet Explorer") ? "IE": BrowserName;
System.out.println("BROWSER NAME IS XXXXXXXXXXXXXXXXXXXXXXXXXXXXX " + BrowserName);
// Opening spreadsheet
Sheet sheetName = workBook.getSheet(sModuleName);
// Collecting row Iterator
rows = sheetName.rowIterator();
// Reading first row of excel as column Titles
if (rows.hasNext()) {
columnNames = this.getAllColumnTitles(rows.next().cellIterator());
}
// Reading rest of rows as column values
while (rows.hasNext()) {
// getting next row
Row row = rows.next();
// converting cell type to String type to read cell value as string
row.getCell(columnNames.indexOf("action")).setCellType(
Cell.CELL_TYPE_STRING);
// checking if multiple cell has right value for paramiterziation to
// update row
if (String.valueOf(row.getCell(columnNames.indexOf("action")))
.equalsIgnoreCase(sActionName)) {
// updating row
row.getCell(columnNames.indexOf(BrowserName.toLowerCase() + "_passfail")).setCellValue(sStatus);
}
}
WritingExcel();
}
/**
* getMappedColValues method to retrieve map object including MappedFields
* type of object with first primary identifyable column name. This will be
* handled by SqlSheet API
*
* @param sheetname
* @return
* @throws Exception
*/
public Map<String, MappedFields> getMappedColValues(String sheetname)
throws Exception {
String strQuery = "SELECT * FROM " + this.getSheetFormat(sheetname);
Map<String, MappedFields> returnMap = new HashMap<String, MappedFields>();
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
resultSet = st.executeQuery(strQuery);
while (resultSet.next()) {
MappedFields mapFields = new MappedFields(resultSet.getString(2),
resultSet.getString(3), resultSet.getString(4));
returnMap.put(resultSet.getString(1), mapFields);
}
resultSet.close();
return returnMap;
}
/**
* getRowCount method to get total rows in sheet. This will be handled by
* SqlSheet API
*
* @param strSheetName
* @return
* @throws SQLException
*/
public int getRowCount(String strSheetName) throws SQLException {
int totalRow = 0;
String strQuery = "SELECT * FROM " + this.getSheetFormat(strSheetName);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
while (resultSet.next())
totalRow++;
resultSet.close();
return totalRow;
}
/**
* getRowCount method to get total rows in sheet. This will be handled by
* SqlSheet API
*
* @param strSheetName
* @return
* @throws SQLException
*/
public int getActiveTCRowCount(String groupName) throws SQLException {
String module, testCategory, riskLevel;
module = groupName.split("_")[0];
testCategory = groupName.split("_")[1];
riskLevel = groupName.split("_")[2];
String strQuery = "SELECT * FROM " + this.getSheetFormat(module);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
int rowIndex= 0;
while (resultSet.next()) {
if (testCategory.equalsIgnoreCase(resultSet.getString("TestCategory")) &&
riskLevel.equalsIgnoreCase(resultSet.getString("RiskLevel")) &&
"1".equalsIgnoreCase(resultSet.getString("Enabled"))){
rowIndex++;
}
}
return rowIndex;
}
/**
* getAllRowValue method to get all rows of parameterized sheet.
*
* @param strSheetName
* @return
* @throws SQLException
*/
public List<Map<String, String>> getAllRowValue(String strSheetName)
throws SQLException {
List<Map<String, String>> returnRowList = new ArrayList<Map<String, String>>();
String strQuery = "SELECT * FROM " + this.getSheetFormat(strSheetName);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
while (resultSet.next()) {
int columntCount = resultSetMetaData.getColumnCount();
Map<String, String> map = new HashMap<String, String>();
for (int i = 1; i <= columntCount; i++) {
map.put(resultSetMetaData.getColumnName(i),
resultSet.getString(i));
}
returnRowList.add(map);
}
resultSet.close();
return returnRowList;
}
/**
* getPreDataSelectedModules method to get list of module. This will be
* handled by SqlSheet API
*
* @return
* @throws SQLException
*/
public List<String> getPreDataSelectedModules() throws SQLException {
List<String> listReturn = new ArrayList<String>();
String product = DriverScript.product;
String productExecutionconfig = product + "ExecutionConfig";
// TO DO.. how to execute Where in SQL Query in JAVA 8
String strQuery = "SELECT * FROM " + this.getSheetFormat(productExecutionconfig);
/* + " WHERE CreateAutomationPreData='Yes' ORDER BY Ranking"; */
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
while (resultSet.next()) {
// Temporary solution until Where clause working in SQL Query
if ("Yes".equalsIgnoreCase(resultSet
.getString("CreateAutomationPreData")))
listReturn.add(resultSet.getString("ModuleName"));
}
resultSet.close();
return listReturn;
}
/**
* getAllRowValueForModules method to get list of module columns based on
* provided strWhreCluase including module names. This will be handled by
* SqlSheet API
*
* @param strSheetName
* @param strWhereClause
* @return
* @throws SQLException
*/
public List<Map<String, String>> getAllRowValueForModules(
String strSheetName, String strWhereClause) throws SQLException {
// Fetching module name values from strWhereClause parameter.
List<String> moduleNames = new ArrayList<String>();
Matcher p = Pattern.compile("'(.*?)'").matcher(strWhereClause);
while (p.find()) {
moduleNames.add(p.group().replace("'", "").replace("%", "").toLowerCase());
}
List<Map<String, String>> returnRowList = new ArrayList<>();
String strQuery = "SELECT * FROM " + this.getSheetFormat(strSheetName);
/* + "WHERE " + strWhereClause; */
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
while (resultSet.next()) {
if (moduleNames.contains(resultSet.getString(2).toLowerCase())) {
int columntCount = resultSetMetaData.getColumnCount();
Map<String, String> map = new HashMap<>();
for (int i = 1; i < columntCount; i++) {
map.put(resultSetMetaData.getColumnName(i),
resultSet.getString(i));
}
returnRowList.add(map);
}
}
resultSet.close();
return returnRowList;
}
/**
* getAllColumnTitles method to provide all column names in
* ArrayList<String> object This will be used by methods where only POI
* worked.
*
* @param cells
* @return
*/
private ArrayList<String> getAllColumnTitles(Iterator<Cell> cells) {
// Temporary variable to send
ArrayList<String> columns = new ArrayList<String>();
// filling value of cells from parameter to arrayList<String>
while (cells.hasNext()) {
Cell cell = cells.next();
columns.add(cell.getStringCellValue().toLowerCase());
}
// returning list of columns
return columns;
}
private String getSheetFormat(String sheetName){
if (System.getProperty("java.version").contains("1.8"))
return sheetName;
else
return "[" + sheetName + "$]";
}
/** updateAnyColumnValue method to update any column value for single row or all rows
* @param sheetNm -> Name of Sheet
* @param columnNm -> Name of column to be updated with value
* @param ParamValue -> Value to be updated to for given column name
* @param ParamName -> Value of row identifier from frist column. If empty, assumed that all rows should be updated of given column with ParamValue
* @throws Exception
* @author Mitul Thesiya
*/
public void updateAnyColumnValue(String sheetNm, String columnNm, String ParamValue, String... ParamName) throws Exception{
// Declaring Variables
String paramName = ParamName.length > 0 ? ParamName[0]: "";
Iterator<Row> rows = null;
ArrayList<String> columnNames = new ArrayList<String>();
// Opening spreadsheet
Sheet sheetName = workBook.getSheet(sheetNm);
// Collecting row Iterator
rows = sheetName.rowIterator();
// Reading first row of excel as column Titles
if (rows.hasNext()) { columnNames = this.getAllColumnTitles(rows.next().cellIterator()); }
boolean isForSingleRow = !paramName.isEmpty();
// Reading rest of rows as column values
while (rows.hasNext()) {
// getting next row
Row row = rows.next();
//if ParamName parameter is found with row identifier value from first column by default
if(isForSingleRow) {
// converting cell type to String type to read cell value as string
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
// checking if ParamName column title has same keyName of field as from parameter
if (String.valueOf(row.getCell(0)).equalsIgnoreCase(paramName)) {
// updating row
row.getCell(columnNames.indexOf(columnNm.toLowerCase())).setCellValue(ParamValue);
break;
}
}
else //Else update each row turn by turn in loop
row.getCell(columnNames.indexOf(columnNm.toLowerCase())).setCellValue(ParamValue);
}
WritingExcel();
}
public void updatedDataIncrementNumbers(String sheetNm, String ParamName, String ParamValue) throws Exception{
// Declaring Variables
Iterator<Row> rows = null;
ArrayList<String> columnNames = new ArrayList<String>();
// Opening spreadsheet
Sheet sheetName = workBook.getSheet(sheetNm);
// Collecting row Iterator
rows = sheetName.rowIterator();
// Reading first row of excel as column Titles
if (rows.hasNext()) { columnNames = this.getAllColumnTitles(rows.next().cellIterator()); }
// Reading rest of rows as column values
while (rows.hasNext()) {
// getting next row
Row row = rows.next();
// converting cell type to String type to read cell value as string
row.getCell(columnNames.indexOf("paramname")).setCellType(Cell.CELL_TYPE_STRING);
// checking if ParamName column title has same keyName of field as from parameter
if (String.valueOf(row.getCell(columnNames.indexOf("paramname"))).equalsIgnoreCase(ParamName)) {
// updating row
//if(ParamValue.length() != 0) {row.getCell(columnNames.indexOf("paramname")+1).setCellValue(ParamValue);}
row.getCell(columnNames.indexOf("paramname")+1).setCellValue(ParamValue);
break;
}
}
WritingExcel();
}
public int getPriorityOfTC(String actionName, String groupName) throws Exception{
String module, testCategory, riskLevel;
module = groupName.split("_")[0];
testCategory = groupName.split("_")[1];
riskLevel = groupName.split("_")[2];
int lastPriority = this.getMaxPriorityOfModule(module, testCategory, riskLevel);
String strQuery = "SELECT * FROM " + this.getSheetFormat(module);
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
Map<String, Integer> foundTestMethods = new LinkedHashMap();
try{
while (resultSet.next()) {
//if (resultSet.getString("Action").toLowerCase().equalsIgnoreCase(actionName.toLowerCase()) &&
if (testCategory.equalsIgnoreCase(resultSet.getString("TestCategory")) &&
riskLevel.equalsIgnoreCase(resultSet.getString("RiskLevel")) &&
"1".equalsIgnoreCase(resultSet.getString("Enabled"))){
foundTestMethods.put(resultSet.getString("Action"), resultSet.getString("ExecutionPriority").isEmpty() ? 0 : Integer.valueOf(resultSet.getString("ExecutionPriority")));
}
}
Integer[] uniquePriorityNumbers = foundTestMethods.values().stream().sorted().distinct().toArray(Integer[]::new);
int setPriroity = lastPriority;
for(int currentNumber : uniquePriorityNumbers){
if(currentNumber == foundTestMethods.get(actionName)){
for(Entry<String, Integer> keyValue : foundTestMethods.entrySet()){
if(keyValue.getValue() == currentNumber){
setPriroity++;
if(keyValue.getKey().equalsIgnoreCase(actionName)){
break;
}
}
}
break;
}
setPriroity += (int) foundTestMethods.values().stream().filter(e -> e.compareTo(currentNumber)== 0).count();
}
return setPriroity;
}
catch(Exception ex){
return lastPriority; //No matched row having same action name found
}
}
public int getMaxPriorityOfModule(String moduleName, String testCategory, String riskLevel) throws Exception{
int maxEligibleRowCount = 0;
int loopCount = Integer.valueOf(DriverScript.listModule.stream().filter(e -> moduleName.equalsIgnoreCase(e.getStrModuleName()) &&
testCategory.equalsIgnoreCase(e.getStrTestCat()) &&
riskLevel.equalsIgnoreCase(e.getStrRiskLevel())).findAny().get().getModulePriority());
for(int i=0; i<loopCount; i++){
String strQuery = "SELECT * FROM " + this.getSheetFormat(DriverScript.listModule.get(i).getStrModuleName());
st = con.createStatement();
resultSet = st.executeQuery(strQuery);
try{
while (resultSet.next()) {
if ("1".equalsIgnoreCase(resultSet.getString("Enabled"))){
maxEligibleRowCount++;
}
}
}
catch(Exception ex){
return maxEligibleRowCount; //No matched row having same action name found
}
}
return maxEligibleRowCount;
}
}
答案 0 :(得分:0)
列名与预期不符。 ArrayList columnNames
既不包含
columnNames.indexOf("action")
或
columnNames.indexOf(BrowserName.toLowerCase() + "_passfail")
,以便indexOf
返回-1
。因此,IllegalArgumentException
中的getCell
。请更正Excel文件中的列名称,并考虑针对此类情况进行错误处理。