I have following code to read .csv and transform it to Excel:
#Grab("org.apache.poi:poi:5.0.0")
#Grab("org.apache.poi:poi-ooxml:5.0.0")
#Grab("com.opencsv:opencsv:4.6")
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import com.opencsv.CSVReader;
def flowFile = session.get()
if(!flowFile)
return
flowFile = session.write(flowFile, { inputStream, outputStream ->
try {
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
CSVReader csvReader = new CSVReader(new InputStreamReader(inputStream));
sxssfWorkbook.setCompressTempFiles(true);
SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet("Sheet");
sxssfSheet.setRandomAccessWindowSize(100);
String[] strHeaders = null;
String[] dataRow = null;
int rowNum = 0;
while ((dataRow = csvReader.readNext()) != null) {
if (rowNum == 0) strHeaders = dataRow;
Row currentRow = sxssfSheet.createRow(rowNum);
for (int i = 0; i < dataRow.length; i++) {
String cellValue = dataRow[i];
currentRow.createCell(i).setCellValue(cellValue);
}
rowNum++;
}
int lastRow = rowNum -1;
int lastCol = strHeaders.length -1;
AreaReference areaReference = new AreaReference(new CellReference(0, 0), new CellReference(lastRow, lastCol), SpreadsheetVersion.EXCEL2007);
XSSFWorkbook xssfWorkbook = sxssfSheet.getWorkbook().getXSSFWorkbook();
XSSFSheet xssfSheet = xssfWorkbook.getSheet(sxssfSheet.getSheetName());
XSSFTable xssfTable = xssfSheet.createTable(areaReference);
//xssfTable.updateHeaders(); // this cannot work since xssfSheet does not contain any data until now
for (int i = 0; i < strHeaders.length; i++) {
String columnHeader = strHeaders[i];
if (xssfTable.getCTTable().getTableColumns().getTableColumnList().size() > i)
xssfTable.getCTTable().getTableColumns().getTableColumnList().get(i).setName(columnHeader);
}
xssfTable.getCTTable().addNewTableStyleInfo();
XSSFTableStyleInfo style = (XSSFTableStyleInfo)xssfTable.getStyle();
style.setName("TableStyleLight9");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
xssfTable.getCTTable().addNewAutoFilter().setRef(areaReference.formatAsString());
sxssfWorkbook.write(outputStream)
} catch (Exception ex) {
ex.printStackTrace();
}
} as StreamCallback)
session.transfer(flowFile, REL_SUCCESS)
But it returns empty flowfile after ExecuteGroovyScript.
Before I tested this in IntelliJ IDEA with Java. But reading from file and saving to file:
FileOutputStream fileout = new FileOutputStream("P:\\test.xlsx");
CSVReader csvReader = new CSVReader(new FileReader("P:\\test.csv"));
So, I guess something wrong with inputstream/outputstream?
P.S. To test some values from cell I decided to write some value to attributes:
...
sxssfWorkbook.write(outputStream);
flowFile.putAttribute('test', sxssfSheet.getRow(5).getCell(1).toString())
...
But flowfile doesn't contain this attribute.
What did I wrong?
Related
I've a simple method to read csv and convert it to Excel:
public static void main(String[] args) throws Exception {
CSVReader csvReader = new CSVReader(new FileReader("P:\\employees.csv"));
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet("Sheet");
String[] dataRow = null;
int rowNum = 0;
while ((dataRow = csvReader.readNext()) != null) {
Row currentRow = sxssfSheet.createRow(rowNum);
for (int i = 0; i < dataRow.length; i++) {
String cellValue = dataRow[i];
currentRow.createCell(i).setCellValue(cellValue);
}
rowNum++;
}
sxssfWorkbook.write(new FileOutputStream("P:\\employees.xlsx"));
}
But there's a problem with cell data type. All my data now represents as text. I want to find columns by their name (for example age, paid_total), not by index, and set numeric (float) data type for these columns. Something like this (sorry for sql-like style, for me it's a simplier to describe): WHEN columnName IN ('age', 'paid_total') SET allColumnType AS NUMERIC. How can I do this? Or it's only possible with indexes?
CSV files always are plain text files without data types. But if you exactly know which column should be which data type, then a type safe Excel sheet can be created. This can be achieved by column indes as well as by column header. To detect types by column header, those headers wolud must be into a separate data structure. But this will always be benefical.
Let's take the example employees.csv from here: https://gist.github.com/kevin336/acbb2271e66c10a5b73aacf82ca82784.
Then following should work:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.streaming.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import com.opencsv.CSVReader;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
class CreateExcelFromCSVDifferentDataTypes {
public static void main(String[] args) throws Exception {
try (
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); FileOutputStream fileout = new FileOutputStream("./employees.xlsx");
CSVReader csvReader = new CSVReader(new FileReader("./employees.csv"));
) {
sxssfWorkbook.setCompressTempFiles(true);
CellStyle dateStyle = sxssfWorkbook.createCellStyle();
dateStyle.setDataFormat(sxssfWorkbook.getCreationHelper().createDataFormat().getFormat("dd-MMM-yy"));
SXSSFSheet sxssfSheet = sxssfWorkbook.createSheet("Sheet");
sxssfSheet.setRandomAccessWindowSize(100);
String[] strHeaders = null;
String[] dataRow = null;
int rowNum = 0;
while ((dataRow = csvReader.readNext()) != null) {
if (rowNum == 0) strHeaders = dataRow;
Row currentRow = sxssfSheet.createRow(rowNum);
for (int i = 0; i < dataRow.length; i++) {
String cellValue = dataRow[i];
if (rowNum > 0 && "HIRE_DATE".equals(strHeaders[i])) {
DateTimeFormatter formatter= new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yy").toFormatter(java.util.Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(cellValue, formatter);
currentRow.createCell(i).setCellValue(localDate);
currentRow.getCell(i).setCellStyle(dateStyle);
} else if (rowNum > 0 && "SALARY".equals(strHeaders[i])) {
double d = Double.valueOf(cellValue);
currentRow.createCell(i).setCellValue(d);
} else {
currentRow.createCell(i).setCellValue(cellValue);
}
}
rowNum++;
}
sxssfWorkbook.write(fileout);
sxssfWorkbook.dispose();
}
}
}
I am using Apache Nifi to extract data SQL query into XLS file.
I use ExecuteQuery to extract data into Avro, then to CSV using CSV RecordWriter
Now I should to have my data in an XLS file, to do, I am using this Groovy script but it's not working:
// import org.apache.commons.io.IOUtils
import java.nio.charset.*
// import java.text.SimpleDateFormat
import java.io.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
def flowFile = session.get()
if(!flowFile) return
flowFile = session.write(flowFile, {inputStream, outputStream ->
try {
inputStream.writeTo(outputStream)
// i tried also outputStream.write(inputStream)
//i tried also to retrieve the excel file with:
//Workbook wb = WorkbookFactory.create(inputStream)
//and write with : outputStream.write(wb)
}
catch(e) {
log.error("Error during processing", e)
session.transfer(flowFile, REL_FAILURE)
}
} as StreamCallback)
session.transfer(flowFile, REL_SUCCESS)
I have this error:
Edit:
I changed my script and had an other error:
#Grapes(#Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
#Grapes(#Grab(group='com.opencsv', module='opencsv', version='4.2'))
import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.streaming.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils
def flowFile = session.get()
def date = new Date()
if(!flowFile) return
flowFile = session.write(flowFile, {inputStream, outputStream ->
SXSSFSheet sheet1 = null;
CSVReader reader = null;
Workbook wb = null;
String generatedXlsFilePath = "/home/";
FileOutputStream fileOutputStream = null;
def filename = flowFile.getAttribute('filename')
def path = flowFile.getAttribute('path')
def nextLine = ''
reader = new CSVReader(new FileReader(path+filename), ',');
//Workbook wb = WorkbookFactory.create(inputStream,);
//Sheet sheet1 = wb.createSheet("Feuille");
wb = new SXSSFWorkbook(inputStream);
sheet1 = (SXSSFSheet) wb.createSheet('Sheet');
def rowNum = 0;
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}
//fileOutputStream = new FileOutputStream(generatedXlsFilePath.trim());
//wb.write(fileOutputStream);
generatedXlsFilePath = generatedXlsFilePath + 'SAISIE_MAGASING.XLS'
outputStream = new FileOutputStream(generatedXlsFilePath.trim());
wb.write(outputStream);
wb.close();
//fileOutputStream.close();
outputStream.close();
reader.close();
//outputStream.close();
inputStream.close();
} as StreamCallback)
flowFile = session.putAttribute(flowFile, 'filename', filename)
The new error:
Thanks to #dagget
This is the worked script:
#Grapes(#Grab(group='org.apache.poi', module='poi-ooxml', version='3.9'))
import com.opencsv.CSVReader
#Grapes(#Grab(group='com.opencsv', module='opencsv', version='4.2'))
//#Grapes(#Grab(group='org.apache.commons', module='lang', version='3.12.0'))
#Grapes(#Grab(group='commons-lang', module='commons-lang', version='2.4'))
import org.apache.commons.lang.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.streaming.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.extractor.*
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.nio.charset.*
import java.io.*
import org.apache.commons.io.IOUtils
def flowFile = session.get()
def date = new Date()
if(!flowFile) return
flowFile = session.write(flowFile, {inputStream, outputStream ->
SXSSFSheet sheet1 = null;
CSVReader reader = null;
Workbook wb = null;
def nextLine = ''
reader = new CSVReader( inputStream.newReader('UTF-8') );
wb = new SXSSFWorkbook();
sheet1 = (SXSSFSheet) wb.createSheet('Sheet');
def rowNum = 0
while((nextLine = reader.readNext()) != null) {
Row currentRow = sheet1.createRow(rowNum++);
for(int i=0; i < nextLine.length; i++) {
if(NumberUtils.isDigits(nextLine[i])) {
currentRow.createCell(i).setCellValue(Integer.parseInt(nextLine[i]));
} else if (NumberUtils.isNumber(nextLine[i])) {
currentRow.createCell(i).setCellValue(Double.parseDouble(nextLine[i]));
} else {
currentRow.createCell(i).setCellValue(nextLine[i]);
}
}
}
wb.write(outputStream);
reader.close();
} as StreamCallback)
def filename = 'toto.xlsx'
flowFile = session.putAttribute(flowFile, 'filename', filename)
session.transfer(flowFile, REL_SUCCESS)
When I run my SOAP UI project, it works fine and it updates the result i.e pass or fail in the specific column however whatever formula I have written which will take input from pass / fail result is not getting updated.
Can you please let me know any reason?
I am using SOAP UI 5.4
The code is given below
import jxl.*;
import java.io.*;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.*;
import static org.apache.poi.ss.usermodel.CellStyle.*;
import static org.apache.poi.ss.usermodel.IndexedColors.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import groovy.json.*;
import groovy.utils.*;
def soapTestCase = context.testCase
def requestPropertyVariable = soapTestCase.getTestStepByName("requestProperty")
def globalProperties = com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils.globalProperties
def responseText = context.expand('${responseText}')
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
def testDataID = globalProperties.getPropertyValue("testDataID")
def testCaseID = globalProperties.getPropertyValue("testCaseID")
int outputRowCount = Integer.parseInt((requestPropertyVariable.getPropertyValue("outputRowCount")))
def responseStatus = testRunner.testCase.getTestStepByName(testCaseID).getTestRequest().response.responseHeaders.find{ it.key == "#status#" }?.value.getAt(0)
int k = Integer.parseInt((requestPropertyVariable.getPropertyValue("outIteration")))
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
def inputxlsh = inptDataWb.getSheetAt(2);
def outputxlsh = inptDataWb.getSheetAt(3);
String otestDataID = outputxlsh.getRow(k+1).getCell(0);
String eleName = outputxlsh.getRow(k+1).getCell(1);
DataFormatter formatter = new DataFormatter();
String expectedResult = formatter.formatCellValue(outputxlsh.getRow(k+1).getCell(2));
String mulEleFLg = outputxlsh.getRow(k+1).getCell(4);
//Validate results
if (responseStatus == "HTTP/1.1 200 OK") {
log.info "Response status code check pass"
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def responseHolder = groovyUtils.getXmlHolder(testRunner.testCase.testSteps[testCaseID].testRequest.response.getContentAsXml())
def tagElement = responseHolder.getNodeValue(eleName) as String //tagElement is a value of a tag
if(mulEleFLg=="Y"){
responseResultArray = tagElement
multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k)
}else{
if(expectedResult==tagElement.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
xlOwb.close();
}else{
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]',''));
log.info "Expected Result is " + expectedResult + " but actual result is " + tagElement.toString().replaceAll('\\[','').replaceAll('\\]','')
inptDataWb.write(xlOwb);
xlOwb.close();
}
}
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateAll();
inptDataWb.setForceFormulaRecalculation(true);
log.info "Refreshed"
}
}
}
}
}
def multiElementValidation(expectedResult, responseResultArray, inptDataWb, outputxlsh, inputFilePath, k){
int resResArrCnt = responseResultArray.size()
FileOutputStream xlOwb = new FileOutputStream(new File(inputFilePath));
boolean match = false;
if(resResArrCnt==1){
for (item in responseResultArray)
{
for (itemOfItem in item){
log.info itemOfItem
if(expectedResult==itemOfItem.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
}else{
for (item in responseResultArray)
{
if(expectedResult==item.toString().replaceAll('\\[','').replaceAll('\\]','').trim()){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("P");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("");
inptDataWb.write(xlOwb);
match = true;
break;
}
}
}
if(!match){
wrtResult = outputxlsh.getRow(k+1).getCell(3);
wrtResult.setCellValue("F");
wrtResult = outputxlsh.getRow(k+1).getCell(5);
wrtResult.setCellValue("Expected Result is " + expectedResult + " but not exist in the array");
log.info "Expected Result is " + expectedResult + " but not exist in the array"
inptDataWb.write(xlOwb);
}
xlOwb.close()
}
def evaluateWorkbook(){
def inputFilePath = globalProperties.getPropertyValue("inputFilePath")
FileInputStream xlwb = new FileInputStream(new File(inputFilePath));
def inptDataWb = new HSSFWorkbook(xlwb);
FormulaEvaluator evaluator = inptDataWb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : inptDataWb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
evaluator.evaluateFormulaCell(c);
log.info "Refreshed the cell"
}
}
}
}
}
I have handle it in excel macro vba under openworkbook. So the workbook formula get updated when the user opens the workbook
This is actually not a question but solution proposal: I found workaround to read set of data from excel. in this case there is no need for multiple users or data variation but read parameters to create a validation environment.
ok, solution is to save excel file to html format and then let the Selenium IDE to read parameters from that. Users needs only to agree the same filename to be used.
1) you should add "Apache POI" jar files in order to read your excel through java.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReadExample {
#SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws Exception {
String filename = "E:\\data.xls";
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExelData(sheetData);
}
private static void showExelData(List sheetData) {
int sum = 0;
for (int i = 0; i < sheetData.size(); i++) {
List<XSSFCell> list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
XSSFCell cell = (XSSFCell) list.get(j);
if(cell.getCellType()==0)
{
sum += cell.getNumericCellValue();
}
}
System.out.println("");
System.out.println("Sum Value is:" +sum);
}
}
}
Change the file path.
i hve mentioned my sheet name as "input" change it as per yours
Happy excelling :D
In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}