How to read Excel sheet for specific rows and columns - java

I want to read Excel sheet from specific row number and only want some specific columns value. I tried lots of stuff, but I don't get proper output as expected.
Below is my code snippet:
public class ReadExcel {
File src=new File("F:\\ucd\\UAT_Patch_31012018.xlsx");
XSSFWorkbook wb;
XSSFSheet Sheet1;
FileOutputStream fileOut;
public void ReadExcel1() throws Exception{
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet Sheet1=wb.getSheetAt(0);
int rowcount=Sheet1.getPhysicalNumberOfRows();
int colcount=Sheet1.getRow(0).getPhysicalNumberOfCells();
for(int i=6;i<=9;i++){
for(int j=0;j<=rowcount;j++){
String testdata1=Sheet1.getRow(i).getCell(j).getStringCellValue();
System.out.println(testdata1);
}
}
}
public static void main(String args[]) throws Exception{
ReadExcel read=new ReadExcel();
read.ReadExcel1();
}
}
Excel file format:
File Name Target Server Target Path
abc/Abc.txt 10.0.43.101 /home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/pqr
xyz/Abc.txt /home/urbancode/UrbanCode/Test/DeployableComponent/xyz
I want to save my output in temp.txt file as below:
abc/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/abc
pqr/Abc.txt;/home/urbancode/UrbanCode/Test/DeployableComponent/pqr

Related

By using java selenium how to write data in Excel sheet

How to write data in the excel sheet by using java selenium? , below code is for reading data from excel sheet
After reading data from excel sheet and executing in the website is fine but,
Need: After execution, I want to "WRITE" the status in the excel sheet.
In my library code: 1)how to write code for write data in excel sheet?
2)How to retrive numeric value from excel sheet
below is my code---------------------
package demo1;
public class Exceldriven
{
WebDriver driver;
#Test(dataProvider="website")
public void FAHT(String firstnametest, String lastnametest, String Email String Password) //throws Exception
{ System.setProperty("webdriver.chrome.driver","D:\\selenium\\drivers\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.*****************.com");
Thread.sleep(2000);
driver.findElement(By.xpath("//input[#name='txtFirstName']")).sendKeys(firstnametest);
driver.findElement(By.xpath("//input[#name='txtLastName']")).sendKeys(lastnametest);
driver.findElement(By.xpath("//input[#name='txtEmailID']")).sendKeys(Email);
driver.findElement(By.xpath("//input[#name='txtPhone']")).sendKeys(Phonenumber);
}
#DataProvider(name="website")
public Object[][] passdata() throws Exception
{
Exceldata c1=new Exceldata("D:\\New folder (2)\\Testdata1.xlsx");
int rows=c1.getrowcount(0);
Object[][] data=new Object[rows][3];
for(int i=0;i<rows;i++)
{
data[i][0]=c1.getdata(0,i,0);
data[i][1]=c1.getdata(0,i,1);
data[i][2]=c1.getdata(0,i,2);
data[i][3]=c1.getdata(0,i,3);
}
return data;
}
}
below is my library code----------------------
public class Exceldata
{
XSSFWorkbook wb;
XSSFSheet FAHT;
public Exceldata(String excelpath) throws Exception
{
try
{
File src=new File(excelpath);
FileInputStream fis=new FileInputStream(src);
wb=new XSSFWorkbook(fis);
}
catch (Exception e)
{
System.out.print(e.getMessage());
}
}
public String getdata(int Sheetnumber,int row,int column)
{
FAHT=wb.getSheetAt(Sheetnumber);
String data= FAHT.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getrowcount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row=row+1;
return row;
}
}
Example on how to write in Row 0, Column 0:
FileInputStream fileInputStream = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheet("Sheet1");
sheet.setColumnWidth(0, 1000);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("YourText");
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(new FileOutputStream(file));
fileInputStream.close();
fileOutputStream.close();

Update existing Excel file

I'm trying to update an existing Excel file. I used the code I saw here Writing to an Existing Excel File but I can't call the function from the main activity.
I tried to create a instance from the department.
It is my code of the class
public class ExceLJxL {
public ExceLJxL(){
}
public static void WriteFile(String path) throws BiffException, IOException, RowsExceededException, WriteException {
Workbook wb = Workbook.getWorkbook(new File(path));
WritableWorkbook copy = Workbook.createWorkbook(new File("D:\temp.xls"), wb);
WritableSheet sheet = copy.getSheet(1);
WritableCell cell;
Label l = new Label(1, 1, "");
cell = (WritableCell) l;
sheet.addCell(cell);
copy.write();
copy.close();
wb.close();
}
}
And here I call the function
ExceLJxL exceLJxL= new ExceLJxl();
exceLJxL.WriteFile( "path");
But he doesn't know it

Writing to an excel using Apache POI corrupts the excel file

I am trying to write to excel using Apache POI. The code (below) executes fine, but when I am trying to open the excel, it is showing that the data inside the excel has been corrupted and it cannot be opened.
Excel version : Microsoft Office Excel 2007 and Microsoft Office Excel 2003 (tried both)
Apache POI Version: 3.6
import java.io.FileOutputStream;
import java.io.IOException;
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 WriteExcel{
public String FilePath;
XSSFWorkbook wb= null;
XSSFSheet ws= null;
XSSFRow xr=null;
XSSFCell xc=null;
FileOutputStream fout = null;
public WriteExcel(String FilePath) throws IOException
{
this.FilePath=FilePath;
fout=new FileOutputStream(FilePath);
wb=new XSSFWorkbook();
wb.write(fout);
}
//Write to a specific Cell
public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException
{
ws=wb.createSheet(SheetName);
xr=ws.createRow(RowNum);
xc=xr.createCell(ColNum);
xc.setCellValue(Data);
fout.close();
}
public static void main(String[] args) throws IOException {
WriteExcel WE= new WriteExcel("E://Learning//Learning//SoapUI//TestFiles//Write.xls");
WE.writeToCell("Sheet1", 2, 2, "Pi");
System.out.println("Written");
}
}
; ;
I believe the the code is fine because every time I am executing the code, the "Date Modified" shows the latest time stamp; so I suspect there might be something with versioning of either Microsoft Office (Excel) or Apache POI.
Could you please help?
You need to write your excel to disk after you create the sheets, rows and cells.
public WriteExcel(String FilePath) throws IOException
{
this.FilePath=FilePath;
}
//Write to a specific Cell
public void writeToCell(String SheetName, int RowNum, int ColNum, String Data) throws IOException
{
fout=new FileOutputStream(FilePath);
wb=new XSSFWorkbook();
ws=wb.createSheet(SheetName);
xr=ws.createRow(RowNum);
xc=xr.createCell(ColNum);
xc.setCellValue(Data);
wb.write(fout);
fout.close();
}

Can some one please provide codes/logic to retrive excel(.xlsx) data like ""driver.findElement(By.id("")).sendkeys(getExceldata(row,column));"

Can some one please provide codes/logic to retrieve Excel (.xlsx) data. I need the data to be retrieved in such a way that I can get the value and pass it any where in code for testing web page. This is the code how I need to get:
driver.findElement(By.id("")).sendkeys(getExceldata(row, column));
I just need to define the row and column and it should get the data from Excel sheet by using any method like getExceldata(1,2)
public String cellValue(String filepath,String sheetname,int r,int c)
{
try{
FileInputStream fis = new FileInputStream(new File(filepath));
book = WorkbookFactory.create(fis);
sh = book.getSheet(sheetname);
System.out.println(sh.getSheetName());
row = sh.getRow(r);
cell = row.getCell(c);
return cell.getStringCellValue();
}catch(Exception e)
{
return null;
}
}
public int getRows(String filepath,String sheetname)
{
try{
FileInputStream fis= new FileInputStream(filepath);
book= new XSSFWorkbook(fis);
return book.getSheet(sheetname).getLastRowNum();
}
catch(Exception e)
{
return 0;
}
----------------------------New class below--------------------------------
WebDriver driver;
Excel excel= new Excel();
public static String filepath="‪D:\\Chinmaya Work\\Work Space\\simpleProject\\src\\Newcustomerdata.xlsx";
public static String sheetname="newcusotomer";
public void setUp() throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("http://www.demo.guru99.com/V4/index.php");
Thread.sleep(5000);
}
public void loginToApplication()
{
Homepagegurru99 home=new Homepagegurru99(driver);
home.enterUsername("mngr45812");
home.enterPassword("chinu#221");
home.clickLoogin();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void gotoNewcustomepage()
{
Dashbardgurru99 dash=new Dashbardgurru99(driver);
dash.gotonewCustomerpage();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void createNewcustomer()
{
Newcustomeradd create=new Newcustomeradd(driver);
int rowCount=excel.getRows(filepath, sheetname);
System.out.println(rowCount);
create.eneterCustomername(excel.cellValue(filepath, sheetname, 2,0));
create.selectSex();
create.enterDob(excel.cellValue(filepath, sheetname, 3,0));
create.enterAddress(excel.cellValue(filepath, sheetname, 4,0));
create.enterCity(excel.cellValue(filepath, sheetname, 5,0));
create.enterState(excel.cellValue(filepath, sheetname, 6,0));
create.enterPin(excel.cellValue(filepath, sheetname, 7,0));
create.enterMobileno(excel.cellValue(filepath, sheetname, 8,0));
create.enterEmail(excel.cellValue(filepath, sheetname, 9,0));
create.enterPassword(excel.cellValue(filepath, sheetname, 10,0));
create.clickSubmit();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
}
public void logOut()
{
driver.findElement(By.linkText("Log out")).click();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
driver.close();
}
Dependencies (poi-ooxml.jar)
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;
To Persist into an Excel File
fis = new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c1 = row1.createCell(0);
r1c1.setCellValue("Demo");
fis.close();
FileOutputStream fos = new FileOutputStream(new File(outputFile));
workbook.write(fos);
fos.close();
To Retrieve from an Excel File follow the link, Get Cell Value from Excel Sheet with Apache Poi .
HTH

Read an excel sheet in, process it and output it

I am playing around with the jexcel libary
I have tried to code a small program which does the following:
Read an xls File
Make some computaitons in the sheet and write it to another place
public class DataProcessor {
private String inputFile;
private String outputFile;
private Sheet sheet;
private Workbook w;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
sheet = w.getSheet(0);
} catch (BiffException e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Lolonator", 0);
workbook.createSheet("Lolonator123", 1);
workbook.copy(w);
workbook.write();
workbook.close();
}
public static void main(String[] args) throws IOException, WriteException {
ReadExcel test = new ReadExcel();
test.setInputFile("C:/Users/Desktop/sheet1.xls");
test.read();
System.out.println("####################################################");
System.out.println("File read!");
// Write
System.out.println("####################################################");
System.out.println("Start to write the file!");
WriteExcel out = new WriteExcel();
out.setOutputFile("C:/Users/Desktop/sheet2.xls");
out.write();
System.out.println("Please check the result file!");
}
}
However, this does not work. I do not get any output in my sheet, even though my program runs without exception to the end. I really appreciate your answer!!!
In your write function, you are using "inputFile" as parameter to File constructor but you are not initializing it after you create the out object.
So the following line in the write function
File file = new File(inputFile);
should be
File file = new File(outputFile);
Also are you sure that you do not see any errors after running this code. It should be throwing a null pointer exception.
Hope this helps...

Categories