Write in Excel Apache POI - java

i had created script which get element from excel , .
Here is my script
public void readExcel() throws BiffException, IOException {
String script = "return rlSerial;";
WebDriver driver;
String baseUrl;
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
driver = new FirefoxDriver();
baseUrl = "http://website.com/";
String SiteWindow = driver.getWindowHandle();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String FilePath = "D:\\TestData.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
// TO get the access to the sheet
Sheet sh = wb.getSheet(0);
// To get the number of rows present in sheet
int totalNoOfRows = sh.getRows();
int totalNoOfCol=sh.getColumns();
sh.getColumns();
for (int row =1; row < totalNoOfRows; row++)
{
for (int col = 0; col < totalNoOfCol; col++){
if (col == 0)
{
System.out.println("Check for Elink "+sh.getCell(col,row).getContents());
}
if (col == 1) {
driver.get(baseUrl +sh.getCell(col,row).getContents());
}
if (col ==2 ) {
driver.findElement(By.xpath(sh.getCell(col,row).getContents())).click();
for (String PromoWindow : driver.getWindowHandles()) {
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
}
if (col ==3 ) {
String exSerial = (String) ((JavascriptExecutor)driver).executeScript(script);
System.out.println("Actual rlSerial = "+ exSerial + "\t" +"Excpected rlSerial = "+sh.getCell(col,row).getContents());
Assert.assertEquals(exSerial ,sh.getCell(col,row).getContents());
System.out.println("Pass");
driver.close();
driver.switchTo().window(SiteWindow);
}
}
}
}
public static void main(String args[]) throws BiffException, IOException {
runTest DT = new runTest();
DT.readExcel();
}
}
If my test cases pass i want to write Pass on next column and if fail then "Fail".
How to achieve this , what to need to be done !!!

To Achieve this first you have to create a new cell in the given row and then set value as "pass" and "fail" to this cell. Use the following code:
sheet.getRow(rowNumber).createCell(columnNumber).setCellValue("pass");
EDIT:
In your code you are using Assert.assertEquals(actual, expected) function which is used with TestNg Annotations, but you are not using TestNG annotations here, So better way is simply compare your actual and expected strings by using equals() or equalsIgnoreCase() method and set your column pass or fail based on that, Here is the solution you want:
if (col ==3 ) {
String exSerial = (String) ((JavascriptExecutor)driver).executeScript(script);
System.out.println("Actual rlSerial = "+ exSerial + "\t" +"Excpected rlSerial = "+sh.getCell(col,row).getContents());
//Assert.assertEquals(exSerial ,sh.getCell(col,row).getContents());
if(exSerial.equals(sh.getCell(col,row).getContents())){
sh.getRow(row).createCell(totalNoOfCol).setCellValue("Pass");
System.out.println("Pass");
}
else{
sh.getRow(row).createCell(totalNoOfCol).setCellValue("Fail");
System.out.println("Fail");
}
driver.close();
driver.switchTo().window(SiteWindow);
}
And save your worksheet after the end of for loop like that:
FileOutputStream outFile =new FileOutputStream(new File(FilePath ));
wb.write(outFile);
outFile.close();

Related

How to extract data from Excel sheet using Apache POI in java(lookup framing)

public class Array_Learn {
public static void main(String[] args) {
try {
FileInputStream ExcelFile = new FileInputStream(new File("C:\\Users\\Anbu.B\\Desktop\\POI-Test\\mediTask.xlsx"));
XSSFWorkbook book1 = new XSSFWorkbook(ExcelFile);
XSSFSheet sheet = book1.getSheetAt(0);
Iterator<Row> rowiter = sheet.iterator();
while (rowiter.hasNext()) {
XSSFRow row = (XSSFRow) rowiter.next();
if (row.getRowNum() == 2) {
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
XSSFCell cell = (XSSFCell) cellIterator.next();
if (cell.getStringCellValue().contains("|")) {
String split[] = cell.getStringCellValue().split("\\|");
}
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I need this output:
chest&&pain=J90
lung&&pneumonia=J54.9
lungs&&pneumonia=J54.9
bronchi&&pneumonia=J54.9
bronchus&&pneumonia=J54.9
colon&&ascending&tumor=D12.5
colon&&ascending&carcinoma=D12.5
colon&&ascending&cancer=D12.5
colon&&ascending&&tumor&&resection=D12.6
colon&&descending&&tumor&&resection=D12.6
colon&&ascending&&carcinoma&&resection=D12.6
colon&&descending&&carcinoma&&resection=D12.6
colon&&ascending&&cancer&&resection=D12.6
colon&&descending&&cancer&&resection=D12.6
The above code is doing read row and iterate each cell and check cell contains | symbol condition is true the split statement is working but, I need the above exact output. What I did in the above code:
Read the excel file.
Read sheet from the excel file.
then create row iterator.
create cell iterator.
check cell contains | symbol then split that cell strings and store into the string array.
You almost finished your task. The key here to use one of the algorithms to generate combinations. You could find a general description of such algorithms there, or more close examples with strings on java there.
Full code example (recursive algorithm):
The ParsedRow class for calculating of different combinations:
class ParsedRow {
private final List<List<String>> combinations;
private final String suffix;
public ParsedRow(List<List<String>> combinations, String suffix) {
this.combinations = combinations;
this.suffix = suffix;
}
public List<String> combine() {
List<String> res = new ArrayList<>();
combine(res, 0, "");
return res;
}
public void combine(List<String> res, int depth, String current) {
if (combinations.size() == depth) {
res.add(current + "=" + suffix);
return;
}
String delimiter = current.isEmpty() ? "" : "&&";
for (int i = 0; i < combinations.get(depth).size(); i++) {
combine(res, depth + 1, current + delimiter + combinations.get(depth).get(i));
}
}
}
The Main class for reading the xlsx file and printing results
public class Main {
public static void main(String[] args) throws IOException {
try (final FileInputStream file = new FileInputStream("diseases.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file)) {
List<String> finalResult = new ArrayList<>();
for (Row row : workbook.getSheetAt(0)) {
List<List<String>> combinations = new ArrayList<>();
String suffix = "";
for (Cell cell : row) {
if (cell.getColumnIndex() != 4) {
final List<String> strings = Arrays.asList(cell.getStringCellValue().split("\\|"));
combinations.add(strings);
} else {
suffix = cell.getStringCellValue();
}
}
ParsedRow parsedRow = new ParsedRow(combinations, suffix);
finalResult.addAll(parsedRow.combine());
}
for (String line : finalResult) {
System.out.println(line);
}
}
}
}

Java & Excel - Formulas updating

I'm using Apache POI to save data to an excel file. Basic data is being saved fine, but I need to also use formula's.
Its adding the formula in, but its not being evaluated until I refresh the cell (clicking into and pressing enter)
The code I'm using to create the cells. Removed code that's not relevant
public void writeExcel(ClassManager cm) throws FileNotFoundException, IOException {
setupRows();
workbook.setForceFormulaRecalculation(true);
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
workbook.close();
}
public void setupRows() {
setupRow15();
}
public void setupRow15() {
int start = 2;
Row row = sheet.createRow(16);
// Create 1st Cell
Cell cell = row.createCell(0);
cell.setCellValue("templateId = ");
for (int i = 0; i < classes.size(); i++) {
// Get class
Classes c = classes.get(i);
// Create cell
cell = row.createCell(start);
// Set contents
cell.setCellFormula("IF(C3=\"\",\"\",CONCAT($A17,$B17,C" + (start + 1) + ",$B17,$A$16))");
start++;
}
}
It's resulting in the formula
Solved it by running after setting all formulas
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
for (Row r : sheet) {
for (Cell c : r) {
evaluator.evaluateFormulaCell(c);
}
}

some error in for loop to fetch data from excel in selenium

#Test
public void passTest() throws IOException {
File src = new File("F:\\drive f\\DemoReport.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
int rowcount = sheet1.getLastRowNum();
for(int i=1;i<=rowcount;i++) {
String str = sheet1.getRow(i).getCell(2).getStringCellValue();
String str1 = sheet1.getRow(i).getCell(1).getStringCellValue();
double j = sheet1.getRow(i).getCell(3).getNumericCellValue();
fis.close();
String exp1 = "Found";
String exp2 = "Not Found";
if(str.equals(exp1)) {
logger=extent.createTest(str1);
Assert.assertTrue(true);
logger.log(Status.PASS, MarkupHelper.createLabel(str1 + " found at index " + j, ExtentColor.GREEN));
}
else if(str.equals(exp2)) {
logger=extent.createTest(str1);
Assert.assertTrue(true);
logger.log(Status.FAIL, MarkupHelper.createLabel(str1 + "is not found", ExtentColor.RED));
}
}
}
i am using testNG to generate extent report, i have some data in my excel file so i fetch them from excel now if the string fetched from excel is "Found" then my test should pass otherwise fail, but in this code it only fetches the data from the first row in the excel.
You are closing theFileInputStream inside the for-loop. Use fis.close(); after for-loop ends.

unable to get numeric values from excel sheet in selenium webdriver with java

My Java
public class Readexcel {
public void readfile(String filepath, String filename, String sheetname) throws IOException
{
File file = new File(filepath+"\\"+filename);
FileInputStream fis = new FileInputStream(file);
// for creating .xlsx workbook
Workbook wb = new XSSFWorkbook(fis);
// for reading the sheet by its name
Sheet sh = wb.getSheet(sheetname);
//find the total rows in sheet
int rowcount = sh.getLastRowNum()-sh.getFirstRowNum();
// create a loop to create
for(int i=0;i<rowcount+1;i++)
{
Row row= sh.getRow(i);
// create a loop to print cell values
for(int j=0;j<row.getLastCellNum();j++)
{
Cell cell= row.getCell(j);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(row.getCell(j).getStringCellValue() + " ");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(row.getCell(j).getNumericCellValue() + " ");
break;
}
System.out.print(row.getCell(j).getStringCellValue()+"||");
}
System.out.println();
}
}
public static void main(String...strings) throws IOException
{
Readexcel re = new Readexcel();
String filepath = "F://Excelsheet";
re.readfile(filepath,"Book1.xlsx","Sheet1");
}
}
By using above code I am getting an error "cannot get text value from numeric cell". Any Help? Also My Output is not properly alligned. All the String are showing one under one. output should be like
Username Password
john 123
rambo 456
but i am getting output like
Username
password
john
Change your for loop after // create a loop to print cell values comment for this:
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(row.getCell(j).getStringCellValue() + " ");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int)row.getCell(j).getNumericCellValue() + " ");
break;
}
}
Switch is to recognise type of cell. For numeric cells you have to use getNumericCellValue() instead of getStringCellValue()
For the second problem use System.out.print() instead System.out.println() which is used to print what is between the double quotes and move the printing cursor to the next line.
EDIT:
This how my readFile() function looks:
public void readfile(String filepath, String filename, String sheetname) throws IOException {
File file = new File(filepath+"\\"+filename);
FileInputStream fis = new FileInputStream(file);
// for creating .xlsx workbook
Workbook wb = new XSSFWorkbook(fis);
// for reading the sheet by its name
Sheet sh = wb.getSheet(sheetname);
// find the total rows in sheet
int rowcount = sh.getLastRowNum() - sh.getFirstRowNum();
// create a loop to create
for (int i = 0; i < rowcount + 1; i++) {
Row row = sh.getRow(i);
// create a loop to print cell values
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(row.getCell(j).getStringCellValue() + " ");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int)row.getCell(j).getNumericCellValue() + " ");
break;
}
}
System.out.println();
}
}
EDIT 2
Changed System.out.print(row.getCell(j).getNumericCellValue() + " "); for
System.out.print((int)row.getCell(j).getNumericCellValue() + " "); in case Cell.CELL_TYPE_NUMERIC

HTML Formatted Cell value from Excel using Apache POI

I am using apache POI to read an excel document. To say the least, it is able to serve my purpose as of now. But one thing where I am getting struck is extracting the value of cell as HTML.
I have one cell wherein user will enter some string and apply some formatting(like bullets/numbers/bold/italic) etc.
SO when I read it the content should be in HTML format and not a plain string format as given by POI.
I have almost gone through the entire POI API but not able to find anyone. I want to remain the formatting of just one particular column and not the entire excel. By column I mean, the text which is entered in that column. I want that text as HTML text.
Explored and used Apache Tika also. However as I understand it can only get me the text but not the formatting of the text.
Please someone guide me. I am running out of options.
Suppose I wrote My name is Angel and Demon in Excel.
The output I should get in Java is My name is <b>Angel</b> and <i>Demon</i>
I've paste this as unicode to cell A1 of xls file:
<html><p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p></html>
This html line produce this:
This is a test. Will this text be bold or italic
My code:
public class ExcelWithHtml {
// <html><p>This is a test. Will this text be <b>bold</b> or
// <i>italic</i></p></html>
public static void main(String[] args) throws FileNotFoundException,
IOException {
new ExcelWithHtml()
.readFirstCellOfXSSF("/Users/rcacheira/testeHtml.xlsx");
}
boolean inBold = false;
boolean inItalic = false;
public void readFirstCellOfXSSF(String filePathName)
throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(filePathName);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
String cellHtml = getHtmlFormatedCellValueFromSheet(sheet, "A1");
System.out.println(cellHtml);
fis.close();
}
public String getHtmlFormatedCellValueFromSheet(XSSFSheet sheet,
String cellName) {
CellReference cellReference = new CellReference(cellName);
XSSFRow row = sheet.getRow(cellReference.getRow());
XSSFCell cell = row.getCell(cellReference.getCol());
XSSFRichTextString cellText = cell.getRichStringCellValue();
String htmlCode = "";
// htmlCode = "<html>";
for (int i = 0; i < cellText.numFormattingRuns(); i++) {
try {
htmlCode += getFormatFromFont(cellText.getFontAtIndex(i));
} catch (NullPointerException ex) {
}
try {
htmlCode += getFormatFromFont(cellText
.getFontOfFormattingRun(i));
} catch (NullPointerException ex) {
}
int indexStart = cellText.getIndexOfFormattingRun(i);
int indexEnd = indexStart + cellText.getLengthOfFormattingRun(i);
htmlCode += cellText.getString().substring(indexStart, indexEnd);
}
if (inItalic) {
htmlCode += "</i>";
inItalic = false;
}
if (inBold) {
htmlCode += "</b>";
inBold = false;
}
// htmlCode += "</html>";
return htmlCode;
}
private String getFormatFromFont(XSSFFont font) {
String formatHtmlCode = "";
if (font.getItalic() && !inItalic) {
formatHtmlCode += "<i>";
inItalic = true;
} else if (!font.getItalic() && inItalic) {
formatHtmlCode += "</i>";
inItalic = false;
}
if (font.getBold() && !inBold) {
formatHtmlCode += "<b>";
inBold = true;
} else if (!font.getBold() && inBold) {
formatHtmlCode += "</b>";
inBold = false;
}
return formatHtmlCode;
}
}
My output:
This is a test. Will this text be <b>bold</b> or <i>italic</i>
I think it is what you want, i'm only show you the possibilities, i'm not using the best code practices, i'm just programming fast to produce an output.

Categories