Read and write to the same Excel file - java

package jexcel.jxl.nimit;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.LabelCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExcelJxl {
public static void main(String[] args) throws WriteException, IOException, BiffException{
String S="D:\\nimit.xls";
ExcelJxl.WriteFile(S);
}
public static void WriteFile(String path) throws IOException, WriteException, BiffException{
Workbook wb=Workbook.getWorkbook(new File(path));
Sheet sheet=wb.getSheet(0);
String s1=null;
String s2=null;
Cell c1=sheet.getCell(0,0);
Cell c2=sheet.getCell(1,0);
if (c1.getType() == CellType.LABEL)
{
LabelCell lc = (LabelCell) c1;
s1 = lc.getString();
}
if (c2.getType() == CellType.LABEL)
{
LabelCell lb = (LabelCell) c2;
s2 = lb.getString();
}
String s3=s1+s2;
WritableWorkbook copy=Workbook.createWorkbook(new File("D:\\demo.xls"),wb);
WritableSheet Wsheet = copy.getSheet(0);
Label l1=new Label(0,0,s1);
Wsheet.addCell(l1);
Label l2=new Label(1,0,s2);
Wsheet.addCell(l2);
Label l3 = new Label(2, 0,s3);
Wsheet.addCell(l3);
copy.write();
copy.close();
}
}
I'm trying to learn how to read and write to the same Excel file.
I'm taking two strings from one file and putting in the other.
How to put the content into the same file?
I'm creating a new file and then I'm putting the contents.
How to read and write to the same text file?
How to overcome this problem?

read-write lock: http://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock

Related

Cannot fetch the data from excel sheet in automation testing

Please check the code suggest correction:
package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DataDriveFramework {
public void readExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream fis = new FileInputStream(file);
Workbook loginWorkbook=null;
String fileExtension=fileName.substring(fileName.indexOf("."));
if(fileExtension.equals(".xlsx"))
{
loginWorkbook=new XSSFWorkbook(fis);
}
else if(fileExtension.equals("xls"))
{
loginWorkbook=new HSSFWorkbook(fis);
}
Sheet loginSheet=loginWorkbook.getSheet(sheetName);
int rowCount=loginSheet.getLastRowNum()-loginSheet.getFirstRowNum();
for(int i=1;1<rowCount+1;i++)
{
Row row=loginSheet.getRow(i);
String username=row.getCell(0).getStringCellValue();
String password=row.getCell(0).getStringCellValue();
test(username,password);
}
}
public void test(String username, String password)
{
WebDriver driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
String baseURL="https://accounts.google.com";
driver.get(baseURL);
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div/c-wiz/div/div[2]/div/div[2]/div/div[1]/div/div/button/span")).click();
driver.findElement(By.xpath("//*[#id=\"password\"]/div[1]/div/div[1]/input")).sendKeys(password);
driver.findElement(By.xpath("//*[#id=\"passwordNext\"]/div/button/span")).click();
driver.quit();
}
public static void main(String[] args)throws IOException {
DataDriveFramework readFile=new DataDriveFramework();
String filePath="C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\";
readFile.readExcel(filePath, "DataDriven.xls", "Sheet1");
}
}
The code is to fetch the data from excel sheet and login automatically.But I am getting an error--
"Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"
at com.framework.DataDriveFramework.readExcel(DataDriveFramework.java:31)
at com.framework.DataDriveFrame.main(DataDriveFrame.java:60)"
You missed a dot '.' in the below line in readExcel() method:
else if(fileExtension.equals("xls"))
it should be like:
else if(fileExtension.equals(".xls"))

Unable to call the parameters from one class-method to another class-method

I have tried with the below code having two classes once is Class1-TestData and Method1-excel(),
And another call to access the parameters Class2-AdminLoginAction and Method2-Admin_Login().
Here is the problem with I need to call the string parameters like UID and PWD as I marked in the Screenshot attached. But the script showed some error and was unable to access it. So, How can I solve this problem, Am I going to the right approach or any other way? Please do need full as soon as possible.
Script image for two classes
import java.io.IOException;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class AdminLoginAction extends TestData{
WebDriver d;
Date currentdate = new Date();
String Screenshotdate = currentdate.toString().replace(" ", "-").replace(":", "-");
ExtentSparkReporter spark = new ExtentSparkReporter("ExtentReport.html");
ExtentReports extent = new ExtentReports();
#Test()
public void Admin_Login() throws InterruptedException, IOException {
TestData excel = new TestData();
extent.attachReporter(spark);
ExtentTest test = extent.createTest("Launch browswer and access the WeClean Login page");
test.log(Status.PASS, "Launch browser success...!!!");
test.pass("Verified launching browser");
System.setProperty("webdriver.chrome.driver", "D:\\backup\\selenium\\chromedriver.exe");
d = new ChromeDriver();
d.manage().window().maximize();
d.get(URL);
Utils.CaptureScreenshot(d, Screenshotdate + "_Login.png");
d.findElement(By.id("loginUser")).sendKeys(UID);
d.findElement(By.id("password")).sendKeys(PWD);
d.findElement(By.id("loginButton")).click();
Thread.sleep(5000);
Utils.CaptureScreenshot(d, Screenshotdate + "_HomePage.png");
test.log(Status.PASS, "Admin Logged in Successful");
test.pass("Verified Admin logged in");
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
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;
import org.testng.annotations.Test;
public class TestData{
public void excel() throws IOException {
String filePath = System.getProperty("user.dir")+"\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(inputStream);
XSSFSheet sheet=wb.getSheet("Admin_inputs");
XSSFRow row2=sheet.getRow(1);
XSSFCell cell=row2.getCell(0);
double UID= cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
String PWD = cell2.getStringCellValue();
}
You can try like this:
public class TestData {
double UID;
String PWD;
public void excel() throws IOException {
String filePath = System.getProperty("user.dir") + "\\Inputfiles";
File file = new File(filePath + "\\TestData.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheet("Admin_inputs");
XSSFRow row2 = sheet.getRow(1);
XSSFCell cell = row2.getCell(0);
UID = cell.getNumericCellValue();
XSSFCell cell2 = row2.getCell(1);
PWD = cell2.getStringCellValue();
}
}
In Admin_Login() method, am just printing UID and PWD, change the code according to your requirement:
public class AdminLoginAction extends TestData {
#Test()
public void Admin_Login() throws InterruptedException, IOException {
// TestData excel = new TestData(); // you don't need to create this object because you are already inheriting `TestData` class.
excel(); // before using UID and PWD you have to call excel() method.
System.out.println(UID);
System.out.println(PWD);
}
}

How is downcasting/upcasting done between 2 interfaces in Selenium WebDriver in Java in Excel

Interface WritableSheet extends interface Sheet (jxl) library. I want to use the addCell() that is there in
WritableSheet.
But when I try to convert Sheet object to WritableSheet object,I get ClassCastException. I want to know how to typecast between two interfaces.
Below is my code :
package xyz;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class WriteExcel12
{
public static Workbook wb;
public static Sheet s;
public static Cell c;
public static WritableSheet ws;
public static Label l;
public static void main(String[] args) throws BiffException, IOException, RowsExceededException, WriteException
{
File f=new File("D:/Input.xls");
wb=Workbook.getWorkbook(f);
s=wb.getSheet("Data");
//WritableSheet extends Sheet
ws=(WritableSheet)s;//ClassCastException here
//Read cell(0,0) from Sheet named Data
c=s.getCell(0,0);
String a=c.getContents();
//Read cell(0,1) from Sheet named Data
c=s.getCell(1,0);
String b=c.getContents();
//Read cell(0,2) from Sheet named Data
c=s.getCell(2,0);
String d=c.getContents();
//Convert String to integer
int e=Integer.parseInt(a);
System.out.println(e);
int g=Integer.parseInt(b);
System.out.println(g);
int h=Integer.parseInt(d);
System.out.println(h);
//Perform addition
int result=e+g+h;
System.out.println(result);
//Convert result which is it to String
String ans=Integer.toString(result);
// Write String ans to cell(0,3)
l=new Label(3,0,ans);
ws.addCell(l);
}
}
Data.xls
10| 20| 30|
You can create a WritableWorkbook from your Workbook.Then you can get your WritableSheet .
File f=new File("D:/Input.xls");
wb=Workbook.getWorkbook(f);
WritableWorkbook copy = Workbook.createWorkbook(f, workbook);
WritableSheet sheet = copy.getSheet("Data");

Reading excel to list of Hashtable in Java

I have a code to read an excel file and place it in a list Hash tables. The code that I have is:
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ReadExcelTest {
public static Hashtable htable=new Hashtable();
public static List<Hashtable<String,String>> exceldata = new ArrayList<Hashtable<String,String>>();
public static void main() throws IOException{
readexcel(System.getProperty("user.dir")+"//src//config//TestData.xls");
}
#Test
public static void readexcel() throws IOException
{
String inputFile=System.getProperty("user.dir")+"//src//config//TestData.xls";
File inputWorkbook = new File(inputFile);
Workbook w;
Cell firstrowelement = null;
try
{
w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
for (int j = 0; j <sheet.getRows(); j++)
{
for (int i = 0; i < sheet.getColumns(); i++)
{
firstrowelement = sheet.getCell(i, 0);
Cell cell = sheet.getCell(i, j);
htable.put(firstrowelement.getContents(),cell.getContents());
System.out.print(firstrowelement.getContents()+"->"+cell.getContents());
}
System.out.println(firstrowelement.getContents());
exceldata.add(j,htable);
}
//printing the list
for(Hashtable hash :exceldata)
{
Enumeration e = hash.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + hash.get(key));
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
}
}
The output I am getting is all the hash tables in the list are displaying the same data instead of displaying each rows data.
Not exactly sure how to over come this issue. Any help is much appreciated.
You need to make a new htable for every row.
As it is, you keep re-using and updating a single HashTable.
(btw. prefer HashMap to HashTable).

Printing results from PDF box output to a text file

I am working on a class which Parses a PDF document with PDF Box, its purpose is to create a text file (its name is PdfTestFile.txt) with the results. We have gotten it to print the parsed text to the console, but I don't know how to make it write the results to the .txt file that the class creates (name is PdfTestFile.txt).
I tried to use out.print(Text); but it gives me an error saying that:
out cannot be resolved
The class PdfEasyManager calls the class EasySearch in which we see the error mentioned above.
Below is the code that I have where the String Text is what I would like to print to the file PdfTestFile.txt:
Class " PdfEasyManager":
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class PdfEasyManager {
static BufferedWriter writer;
public static void main(String[] args) throws IOException {
//writer = new BufferedWriter(new FileWriter("Evergreen.txt"));
EasySearch easysearch = new EasySearch();
// pdfManager.setFilePath("PDFextTEST.pdf");
System.out.println(easysearch.ToText());
//out.println(easysearch.ToText());
}
}
Class "EasySearch" :
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class EasySearch {
private PDFParser parser;
private PDFTextStripper pdfStripper;
private PDDocument pdDoc ;
private COSDocument cosDoc ;
private String Text ;
private String filePath;
private File file;
static BufferedWriter writer;
//writer = new BufferedWriter(new FileWriter(BLnumber + (date.toString().substring(4, 10))+ ".org"));
public EasySearch() {
}
//public static void main(String args[]) throws Exception{
public String ToText() throws IOException
{
this.pdfStripper = null;
this.pdDoc = null;
this.cosDoc = null;
writer = new BufferedWriter(new FileWriter("PdfTestFile.txt"));
file = new File("C:/Users/Jon Smith/Desktop/Sample.pdf");
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
pdDoc.getNumberOfPages();
pdfStripper.setStartPage(1);// reading text from page 1
// pdfStripper.setEndPage(10);// to 10
pdfStripper.setEndPage(pdDoc.getNumberOfPages());// if you want to get text from full pdf file use this code
Text = pdfStripper.getText(pdDoc);
out.print(Text); //this is the line that gives me the error
return Text;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
You are using out which is not present in your class. Use System.out.print(Text).
Thanks for the help but
writer.write(Text);
solves the issue I was having

Categories

Resources