I am new to Selenium and I am trying to write a code to write data into excel. This code is working. However, it just write on the second row. When I change the value of "String FieldName1 to 3" it doesn't write on the next row. I change the value of header = spreadsheet.createRow(0); to (1) it did write to next row, but it is a pain to do it every time I run my test. What I need is to write the data to the next ROW everytime I run it and change the value of "String FieldName1 to 3". THANKS IN ADVANCE!
Selenium > Java > Maven
public class testBed2 {
#Test
public void writeExcel() throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\ExportExcel.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet( "TestData");
XSSFRow header;
header = spreadsheet.createRow(0);
header.createCell(0).setCellValue("FieldName1");
header.createCell(1).setCellValue("FieldName2");
header.createCell(2).setCellValue("FieldName3");
int rowNumber = 1;
Row row = spreadsheet.getRow(0);
//Column Count
int colCount = row.getLastCellNum();
for (int j = 0; j < colCount; j++) {
System.out.println("Col Count : " + j);
//Row Count
int rowCount = spreadsheet.getLastRowNum() + 1;
for (int i = 0; i < rowCount; i++) {
XSSFRow currentRow = spreadsheet.createRow(rowNumber);
System.out.println("Row Count : " + i);
String FieldName1 = "NAME1";
String FieldName2 = "NAME2";
String FieldName3 = "NAME3";
currentRow.createCell(0).setCellValue(FieldName1);
currentRow.createCell(1).setCellValue(FieldName2);
currentRow.createCell(2).setCellValue(FieldName3);
FileOutputStream fos = new FileOutputStream("C:\\Users\\ExportExcel.xlsx");
workbook.write(fos);
fos.close();
}
}
}
}
I think the reason why your code write just second row is, your close code is in the For loop. If you write close code at the end of {} you will get right answer. :)
Related
I am using selenium and java to scrape data on a specific site, but with the code below I can write only 1 data in the spreadsheet, it is not recording all the data in sequence as it should be.
I can't structure the loop correctly.
public void gravarDados() throws IOException {
int i = 0;
File localPlanilha = new File("tools/resultado_da_pesquisa.xlsx");
FileInputStream planilhaExistente = new FileInputStream(localPlanilha);
XSSFWorkbook plan = new XSSFWorkbook(planilhaExistente);
XSSFSheet sheetExistente = plan.getSheetAt(0);
for (int i = 0; i < inicio; i++) {
// Writing data
sheetExistente.getRow(2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);
plan.write(fechandoArquivo);
}
}
Currently you are getting only the 0th element.
You need to iterate the below with a for loop
TitulosHoteis.get(i).getText());
to write the result to rows and columns.
Please modify it as below
for (int i = 0; i < inicio; i++) {
// Writing data
sheetExistente.getRow(i+2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
}
FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);
plan.write(fechandoArquivo);
As mentioned before you're not iterating over the rows as the row number stays the same in your code, however there is also another problem with your code. You need to check if a row exists and if it doesn't create it before you can set a cell value of that row.
It should look something like this:
for (int i = 0; i < inicio; i++) {
Row row = sheetExistente.getRow(2+i);
if (row == null) sheetExistente.createRow(2+i);
sheetExistente.getRow(2 + i).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
}
I am printing some string values in excel
In excel currently last string is printing, but I need to print them all row by row
Code
for(String a:arrOfStr)
{
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a)
}
keyword
#Keyword
public void demoKey(String name) throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row = sheet.createRow(rowCount+);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
workbook.write(fos);
fos.close();
Now I can get the output like(overriding each value and giving last string )
I want to see like
Try this
for(int i = 0; i < arrOfStr.size(); i++)
{
String a = arrOfStr[i];
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a,i)
}
#Keyword
public void demoKey(String name, int index) throws IOException{
FileInputStream fis = new FileInputStream("path");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.createRow(index + 1);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("path");
workbook.write(fos);
fos.close();
}
}
You have to do in the following manner.
First create a set of rows
Create cell and define the cell data type.
Store the value in the cell
I provide below the structure to store the data row by row.
int rowNumber = 0; // Row number starting with 0
for (i = 0 ; i < 10 ; i++) { //This for loop can be your data set
Row row = sheet.createRow(rowNumber++);
int columnNumber = 0; //Cell or Column number starting with 0
for (j = 0 ; j < 5 ; j++) { //This for loop can be your data set
Cell cell = row.createCell(columnNumber++);
cell.setCellValue("Some string value");
}
}
I am trying to update a column in the excel sheet but only the first row is getting update. The second iteration is not working. Could anyone help me on this? Below is my code that I am trying.
String excelPath = "path";
String YES = "Updated YES";
String NO = "Updated NO";
try {
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
Cell cell = null;
FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
HSSFSheet sheet1 = workSheet.getSheetAt(0);
String data = sheet1.getRow(i+1).getCell(i).toString();
if(data.equals(TCID.get(i))){
cell = sheet1.getRow(i+1).getCell(i+2);
cell.setCellValue(YES);
workSheet.write(output_file);
}else {
cell.setCellValue(NO);
workSheet.write(output_file);
}
}
fis.close();
output_file.close();
workSheet.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My latest code is below. Now it is updating the columns but the last row is not getting updated. What am i missing.
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet1 = workSheet.getSheetAt(0);
//FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
}
fis.close();
//output_file.close();
//workSheet.close();
FileOutputStream output_file =new FileOutputStream(excelPath);
workSheet.write(output_file);
output_file.close();
The row and the column are both keyed off 'i', so you'll be traversing the sheet diagonally.
But certainly do the things the other people are recommending too, they are all good suggestions.
Typically when working with a two dimensional block of information, I find it useful to have one loop for rows and then nested inside that a loop for columns (or vice versa)
e.g.
for (y = startRow; y <= maxRow; y++) {
....
for (x = startCol; x <= maxCol; x++) {
.... // do something to each column in the current row
cell = sheet1.getRow(y).getCell(x);
.....
Ok, so there are a couple of things.
Declare HSSFSheet sheet1 = workSheet.getSheetAt(0); outside of your loop. You are working with the same sheet each iteration of your for loop, so this only has to be invoked once.
Your logic to get the cell data (String data = sheet1.getRow(i+1).getCell(i).toString();) will not return you the same column. On your first iteration, you'll get (R)ow 1 : (C)olumn 0. The next iteration will return R2 : C1, then R2:C2, then R3:C3, etc. Notice the pattern that you are going diagonally down the columns, not vertically.
Rows start at 0.
You only need to workSheet.write(output_file); once you have done all your processing.
If the Row does not exist you will get a NullPointerException
As you are working with a unique Cell each iteration, you just declare it in the loop (so no need for Cell cell = null; outside your loop).
Here is a an example:
try {
FileInputStream fis = new FileInputStream(excelPath);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < 5; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(0);
cell.setCellValue("Updated cell.");
}
}
FileOutputStream output_file = new FileOutputStream(excelPath);
workbook.write(output_file);
output_file.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
I think moving Cell reference inside for loop should fix it for you.
Cell cell = null;
Also you might also need to move outside if-block incase you face NullPointerException in else-block
cell = sheet1.getRow(i+1).getCell(i+2)
Something like this...
HSSFSheet sheet1 = workSheet.getSheetAt(0);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
workSheet.write(output_file)
}
public Object[][] dataProviderMethod() throws IOException {
try {
file = new FileInputStream(new File("/Users/nanthakumar/Documents/workspace/Myna_Admin/src/com/myna/testdata/login.xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
row = sheet.getLastRowNum() + 1;
col = sheet.getRow(0).getLastCellNum();
data = new String[row][col];
for (i = 0; i < row; i++) {
rowvalue = sheet.getRow(i);
for (j = 0; j < col; j++) {
cellValue = rowvalue.getCell(j);
data[i][j] = cellValue.getStringCellValue();
System.out.println("The value is ----->" + data[i][j]);
}
workbook.close();
file.close();
}
} catch (FileNotFoundException nana) {
nana.printStackTrace();
}
return data;
}
This is my code and I tried to add the getnumericalCellvalue() instead of getStringCellValue() but that is not working for me.
first you have to check in the template excel whether the column is number or text.you can get the numerical value if and only if the column is of type number.so change the template excel and try
Hi I am reading Excel file from java using jxl workbook library.Below is the code.
Workbook wb = Workbook.getWorkbook(new File(destFile));
String line = ""; // available
for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
Sheet sheet = wb.getSheet(sheetNo);
System.out.println("Sheet Name is:\t" + sheet.getName());
if(sheet.getName().trim().equals("Store List")){
int columns = sheet.getColumns();
int rows = sheet.getRows();
String data;
for (int row = 0; row < rows; row++) {
for (int col = 1; col < columns; col++) {
data = sheet.getCell(col, row).getContents();
line = line + data + "#";
}
line += "#&#";
}
System.out.println("Entire line is" + line);
}
}
The above code reads row&column data from the excel file and passes it to the service method for further processing.
When I traverse it line-by-line for the empty cell, the Java code throws IndexOutOfBoundException. Please find the java code below which throws exception.
for(int elementCount=4;elementCount<elements.length;elementCount++) {
String strquantity = rowValues[elementCount];
int quantity=0;
if(strquantity.equals("")){
quantity = 0;
} else {
quantity = Integer.parseInt(strquantity);
System.out.println("Quantity value is:\t" + quantity);
}
}
As you the above code exception is thrown at line 2.
I believe that cause is due to workbook library.
After doing some rnd i got the solution,If it is empty cell will get the 0 or null value from jxl API.
As in my code i was looking for empty string
if(strquantity.equals("")){
quantity = 0;
}
now the code changed to below one
if(strquantity.equals(null) || strquantity.equals("0")){
quantity = 0;
}