Writing data in an existing worksheet using JXL and Java - java

I have the code to get data from the worksheet using JXL and Java, but at the end of the process I need to get a data from the page and write to a certain cell in the worksheet.
//reading the worksheet
Workbook workbook = Workbook.getWorkbook(new File("d:/planilha.xls"));
//Indicate the opening of the first worksheet
Sheet sheet = workbook.getSheet(0);
//Count the rows
int linhas = sheet.getRows();
//Start a for loop to scan all rows in the already selected worksheet
for(int i = 1; i < linhas; i++){
//Referencing rows that have content
Cell nome_promocao = sheet.getCell(0, i);
Cell desc_promocao = sheet.getCell(1, i);
Cell tipo_promocao = sheet.getCell(2, i);
Cell dt_inicio = sheet.getCell(3, i);
Cell dt_fim = sheet.getCell(4, i);
Cell aparelho = sheet.getCell(5, i);
Cell idpromo = sheet.getCell(6, i);
//Taking the data from the worksheet
String linhanomepromocao = nome_promocao.getContents();
String linhadescpromocao = desc_promocao.getContents();
String linhatipopromocao = tipo_promocao.getContents();
String linhadtinicio= dt_inicio.getContents();
String linhadtfim = dt_fim.getContents();
String linhaaparelho = aparelho.getContents();
String linhaidpromo = idpromo.getContents();
//Other actions
//Get the id I need on the page and saving in a variable
String numberpromotion = driver.findElement(By.className("link")).getText();
//I need to record this number of the above variable in the corresponding cell (idpromo or linhaidpromo)

Does this provide answer to your question?:
Label label = new Label(6, i, numberpromotion);
sheet.addCell(label);

Related

Reading from excel files using JAVA poi and ignoring empty cells

I was trying to read data from an excel sheet that contains empty cells consider the following code:
File src = new File(path to your file);
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheet("Sheet1");
int rowCount = sheet1.getLastRowNum();
System.out.println("total number of rows is: " + rowCount);
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
System.out.println(data);
}
However, my code also reads the empty cells and displays the value as 0 (The cells have numeric value). How do I make my script read-only cells that are filled and display them while ignoring the ones that are empty?
Thank you in advance
Just update the for loop with an if condition which will check for the value which is getting retrieved from the Cell. PFB the updated for loop.
For Apache POI version 4.x you can try below-
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
Cell cell = sheet1.getRow(i).getCell(1);
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
if(c.getCellType() == CellType.Blank)
{
continue;
}
else{
System.out.println(data);
}
}
For Apache POI version 3.x you can try below-
for(int i = 1; i < rowCount; i++) {
//getcell returns row num and starts from 1
//Also my sheet column contains data in numeric form
Cell cell = sheet1.getRow(i).getCell(1);
int data = (int) sheet1.getRow(i).getCell(1).getNumericCellValue();
if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
continue;
}
else{
System.out.println(data);
}
}

Java - Select the line to read data in JXL

My spreadsheet has a label and I would like to read it from line 2.
But I'm not getting a simple way to do this in JXL, I've read the documentation and can not implement it.
I tried String login = sheet.getCell(0, 2, i).getContents(); but it did not work.
It only reads normally if it only has 2 parameters, specifying the i of the for and column, as: String login = sheet.getCell(0, i).getContents();
Workbook workbook = Workbook.getWorkbook(new java.io.File("tools/file.xls"));
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
for(int i = 0; i < rowCount; i++)
{
String login = sheet.getCell(0, i).getContents();
String password = sheet.getCell(1, i).getContents();
}
workbook.close();
GetCell() method possibilities are:
getCell(int column, int row) - ex. getCell(1,4)
getCell(String loc) - ex. getCell("A4")
There isn't any 3 parameters getCell() method.
If you would like to start scraping from second row, change your "i" value.
Workbook workbook = Workbook.getWorkbook(new java.io.File("aaa.xls"));
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
int startingRowPosition = 2;
for(int i = startingRowPosition; i < rowCount; i++)
{
String login = sheet.getCell(0, i).getContents();
String password = sheet.getCell(1, i).getContents();
System.out.println("Login: " + login + " Password: " + password);
}
workbook.close();

How to have excel formula refresh when new data inserted with Java through Apache POI

I am inserting a list of numbers into a column in Excel (column A) with Java. the following column has a list of average numbers (Column B). Column C has a list of formulas like this: =IF(B1 < 1,0,((A1)-B1)/B1).
In my program, I want to have the formulas in column C re-evaluate after I've input the new data so then I can extract the new cell value into Java. I'm checking to see if any new result in column C is -1.0.
I've tried to use FormulaEvaluator before extracting column C values but I still get the old values. I've also tried writing and closing the workbook and opening it again but that also hasn't worked.
//Pull the values stored procedure
ResultSet rs = dbutils.sqlserverdbvaliation(query, db);
System.out.println("Returned the Result Set");
//Get number of rows in result row to set array size
rs.last();
arraySize = rs.getRow();
rs.beforeFirst();
//Store values from resultSet into an array
int[] dlArray = new int[arraySize];
while(rs.next()) {
//Activity Process Count is name of ResultSet Column
dlArray[count] = rs.getInt("ActivityProcessCount");
count++;
}
//Create workbook
InputStream inp = new FileInputStream("C:\\TestWorkbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(1);
FormulaEvaluator evaluator =
wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateAll();
System.out.println(Arrays.toString(dlArray));
//Write the values from the array to the spreadsheet
int excelCount = 1;
for (int i = 0; i < arraySize ; i++) {
Row row = sheet.getRow(excelCount);
Cell cell = row.getCell(2);
cell.setCellValue(dlArray[i]);
evaluator.evaluateAll();
excelCount++;
}
FileOutputStream fos = new FileOutputStream("C:\\TestWorkbook.xlsx");
evaluator.evaluateAll();
wb.write(fos);
wb.close();
InputStream inp2 = new FileInputStream("C:\\TestWorkbook.xlsx");
Workbook wb2 = WorkbookFactory.create(inp2);
org.apache.poi.ss.usermodel.Sheet sheet2 = wb2.getSheetAt(1);
excelCount = 1;
for (int i = 0; i < arraySize ; i++) {
Row row = sheet2.getRow(excelCount);
Cell cell = row.getCell(4);
if (cell.getNumericCellValue() == -1.0) {
ExcelUtils.setCellStyle(excelPath, sheetName, excelCount, 5,
YELLOW);
}
else {
ExcelUtils.setCellStyle(excelPath, sheetName, excelCount, 5,
GREEN);
}
excelCount++;
}

creating extra excel file using java and POIExcel util if max rows have been exceeded

I want to create an excel document with 5 sheets, the data for the sheets is dynamic and I have a maximum row limit.
currently my approach is creating one sheet at a time, and filling it with data. I am checking if max rows have been exceeded, and creating a new excel document.
However this will not wait to check if the other sheets are also exceeding the max row limit before creating the new workbook
My code samples
private void populateDetailsSheets(String[] data) throws IOException
{
currentRow = getCurrentRow();
rowCount++;
short cellNumber = 0;
for (String value : data)
{
POIExcelUtil.createCellWithContent(currentRow,value,cellNumber++).setCellStyle(contentStyle);
}
writeToFileOnExhaustingMaxRows();
}
private void writeToFileOnExhaustingMaxRows() throws IOException
{
if(sheet.getLastRowNum() + 2 > Integer.valueOf(SystemProperty.MAX_RECORDS_PER_EXCEL))
{
writeToFile();
rowCount = 0;
createWorkbook();
titleStyle = createTitleStyle();
headerStyle = createHeaderStyle();
columnHeaderStyle = createColumnHeaderStyle();
columnHeaderStyle.setBorderLeft(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderRight(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);
contentStyle = createCellStyle();
contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
contentStyle.setBorderTop(CellStyle.BORDER_THIN);
contentStyle.setBorderRight(CellStyle.BORDER_THIN);
contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
rowCount = 0;
createSheet("title sheet");
populateReportSettingsSheet();
rowCount =0;
createSheet(sheetNames[index]);
setColumnWidth();
createColumnHeader();
}
}
I am assuming that you want to jump to next sheet when the sheet one is full. Here the trick.
public class JumpToNewSheet {
private static HSSFSheet allocateNewSheet(HSSFWorkbook wb, String sheetName) {
HSSFSheet sheet = wb.createSheet(sheetName);
/*You can add style here too or write header here*/
return sheet;
}
public HSSFWorkbook exportExcel_xls(MyTable table) {
int cellNumber = 12;
List<TupleData> tuples = table.getTuples();
HSSFWorkbook wb = new HSSFWorkbook();//Whole book
HSSFSheet currentSheet = allocateNewSheet(wb, "SHEET");//Initial sheet
int sheetCounter = 1;//Start at 1 because we already created Initial sheet
int rowCounter = 0;//1st row in sheet
for(TupleData t: tuples) {//Loop through data
if(rowCounter % 65535 == 0) {//Max row reached, build new sheet
//Increase sheetCounter
sheetCounter++;
String new_sheetName = "SHEET_"+sheetCounter;//Name of sheet
currentSheet = allocateNewSheet(wb, new_sheetName);//Point currentSheet to new sheet
//Reset rowCounter to 0
rowCounter = 0;
}
Row row = currentSheet.createRow(rowCounter);
for(int i=0; i <=cellNumber; i++) {
Cell cell = row.createCell(i);
//Write data.......
//.............
}//End inner for loop
rowCounter++;
}//End for loop
}//End exportExcel_xls(MyTable table)
}

Fetching value from webtable and write in excel sheet one by one of each row in a loop

1) I am trying to read the values from the webtable of an appliation and write it into the excel sheet one by one.
2) There are 4 values in each row of the webtable that need to be written to excel sheet, but there are some images in each row that i'm ignoring bu using below code.
text.length()>2
.
3) There will be 200-300 rows in webtable that need to be fetched and written to excel sheet.
This is the code i have tried. But i dont know how to write it into each row of the excel sheet one by one. Please help me in this regard.
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
for (WebElement row : allRows) {
//Get all cell values in each row
List<WebElement> allCells = row.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1){
for (WebElement cell : allCells) {
String text = cell.getText();
if(text.length()>2){
String value = cell.getText();
}
}
}
// locate the test xl file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row = sheet1.getRow(1);
HSSFCell cellEx = row.getCell(0);
if (cellEx == null) {
cellEx = row.createCell(0);
}
cellEx.setCellValue(value);
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
// locate the test xls file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row;
for (int i=0; i<rowSize; i++)
{
WebElement webRow = allRows.get(i);
//Get all cell values in each row
List<WebElement> allCells = webRow.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1)
{
HSSFRow excelRow = sheet1.createRow(i);
for (int j=0; j<allCells.size(); j++)
{
WebElement webCell = allCells.get(j);
String text = webCell.getText();
if(text.length()>2)
{
Cell excelCell = excelRow.createCell();
excelCell.setValue(webCell.getText());
}
}
}
}
sheet1.close();
Read the values from the Web Table of an application and write it in to the excel sheet one by one.There are 5 values in each row of the Web Table and that need to written in Excel sheet. Below is the working code.
System.setProperty("webdriver.chrome.driver","C:\\Users\\Documents\\Selenium jars\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://cosmocode.io/automation-practice-webtable/");
WebElement table = driver.findElement(By.xpath("//*[#id='countries']/tbody"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
int rowcount = rows.size();
FileOutputStream fis = new FileOutputStream(new File("C:\\Users\\Documents\\Selenium\\output.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet("First Sheet");
for (int row = 0; row < rowcount; row++) {
List<WebElement> columns_inrow = rows.get(row).findElements(By.tagName("td"));
int columns_count = columns_inrow.size();
System.out.println("Number of cells in Row " + row + " are " + columns_count);
Row ro = sh.createRow(row);
for (int column = 0; column < columns_count; column++) {
String celltext = columns_inrow.get(column).getText();
System.out.println(
"Cell Value of row number " + row + " and column number " + column + " Is " + celltext);
ro.createCell(column).setCellValue(celltext);
}
System.out.println("===========================");
}
wb.write(fis);
wb.close();
}

Categories

Resources