setCellValue not working - java

i can't set the value of cell ,it works if i try this
if(1==1){
celltofill.setCellValue("test");
}
but once it enters the if condition it displays what's in syso but doesn't insert values in the cell.
any ideas about how can i solve this isssue?
here is my code:
public class testexcel {
public static void main(String[] args) throws InvalidFormatException, IOException, ParseException{
FileInputStream fis = new FileInputStream("D:\\test6.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream("D:\\edit6.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet2 = workbook.getSheetAt(1);
for(int i=1; i <= sheet.getLastRowNum(); i++) {
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell celltofill= row.createCell(5);
Cell cellres= row2.getCell(1);
if((cell.getStringCellValue()).equals(cell2.getStringCellValue())){
System.out.println((cell.getStringCellValue())+" equals "+cell2.getStringCellValue());
celltofill.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("cell filled with "+cellres.getStringCellValue());
celltofill.setCellValue(cellres.getStringCellValue());
}
}
}
workbook.write(fos);
fos.close();
}
}

row.createCell(5) does exactly what it says. It creates a new empty cell every time it is called. And you are calling it for every row in sheet2 again and again although it is a cell in sheet. So even if the criterions are not fullfilled, the new empty cell is been created already in your code.
Maybe:
...
for(int i=1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Cell celltofill= row.getCell(5);
if (celltofill == null) celltofill = row.createCell(5);
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell cellres= row2.getCell(1);
...
will be more what you want?

Related

how to write values obtained using List and Iterator in a excel file using apache poi and selenium webdriver

Hi I need to store a list of values which I obtained from a webpage using List and Iterator using selenium webdriver, I want to store/write those values in a excel sheet
Link of the website:https://www.zigwheels.com/used-car
I have obtained a list of values under popular car models and I need to store it in a excel sheet using apache poi
Coding starts here:
WebElement li=
driver.findElement(By.xpath("//span[text()='Brand and Model']//parent::div//followingsibling::div//child::div[4]/ul"));
List<WebElement> alloptions=li.findElements(By.tagName("li"));
Iterator<WebElement> itr=alloptions.iterator();
while(itr.hasNext()) {
WebElement lii=itr.next();
String list=lii.getText();
System.out.println(list);
Create file, than sheet, then rows, and fill cells in row:
public void CreateNew_Make_BeckupFile() throws IOException
{
String filePath = "filepath.xls";
File f = new File(filePath);
if (!(f.exists() && f.isFile()))
{
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/*
* CreationHelper helps us create instances of various things like DataFormat,
* Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way
*/
CreationHelper createHelper = workbook.getCreationHelper();
for (int p = 0; p < listaTimova.size(); p++) {
// Create a Sheet
// Sheet sheet = workbook.createSheet("Employee");
SheetCreation (workbook, p);
}
// Write the output to a file
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
// Closing the workbook
workbook.close();
outputStream.close();
}
public void SheetCreation (Workbook workbook, int teamNumber)
{
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Sheet Name");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.BLUE.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Create cells
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
headerFont.setColor(IndexedColors.BLACK.getIndex());
headerCellStyle.setFont(headerFont);
for (int u = 0; u < listaTimova.get(teamNumber).listaIgracaTima.size(); u++)
{
Row headerRow2 = sheet.createRow(u + 1);
**RowCreation(headerRow2, teamNumber, u, 0);**
}
for(int i = 0; i < columns.length; i++)
{
sheet.autoSizeColumn(i);
}
}
**public void RowCreation(Row row, int teamNumber, int playerNumber, int cellNumber)**
{
row.createCell(cellNumber, CellType.STRING).setCellValue("Any value for cell");
row.createCell(cellNumber+1, CellType.STRING).setCellValue("next cell in row value...");
}

How can I print the passing string row by row in excel

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");
}
}

Reading and Validating Rows with Aspose JAva

I am trying to read and validate a Row with Aspose Cells Java, but I have never used ir before and de documentation is not very clear, it doesn't even show you how to read a Row. Heres what I've done so far:
public static void main(String[] args) {
String dataDir = "C:\\Users\\apoac22836\\Desktop\\";
Workbook wb = new Workbook(dataDir + "Example.xlsm");
Worksheet worksheet = wb.getWorksheets().get("BOM");
int column = 1;
for (int i = 0; i < 40; i++) {
Cell lastCell = worksheet.getCells().endCellInColumn((short) column);
for (int row = 0; row <= lastCell.getRow(); row++) {
Cell cell = worksheet.getCells().get(row, column);
System.out.println(cell.getStringValue());
}
column += 1;
System.out.println("------------------------------------------------");
}
}
I brings the value of the cells by columns.
Well, if you need to efficiently enumerate all the data (non empty values) in a range, rows, cells, you may try to use Range.iterator(), RowCollection.iterator() and Cells.iterator() method to get the iterator for specific range, initialized rows and non empty or initialized cells, see the following sample codes for your reference:
e.g
Sample code:
//Range Iterator.
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
System.out.println(cell.getName() + " is not empty");
}
//Cells Iterator.
Workbook workbook = new Workbook("Book1.xls");
Worksheet sheet = workbook.getWorksheets().get(0);
Cells cells = sheet.getCells();
//Get the iterator from Cells collection
Iterator cellIterator = cells.iterator();
//Traverse cells in the collection
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
//Rows collection Iterator.
String filePath = "c:\\source.xlsx";
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.getWorksheets().get(0);
RowCollection rows = worksheet.getCells().getRows();
Object obj = rows.iterator().next();
Iterator<Row> rowIterator = worksheet.getCells().getRows().iterator();
while(rowIterator.hasNext())
{
Row r = rowIterator.next();
Iterator<Cell> cellIterator = r.iterator();
while(cellIterator.hasNext())
{
Cell cell= cellIterator.next();
System.out.println(cell.getStringValue());
}
}
Hope, this helps a bit.
I am working as support developer/Evangelist at Aspose.

Check if row contains word

I have a spreadsheet and I only want to select rows that have a specific word in one column and another word in another column. At the moment I am only able to check for the word in any cell in the row. How can I check for the presence of the word in a cell in a specific column?
Here is my code
FileInputStream fis = new FileInputStream(new File(filepath));
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt (0);
List<XSSFRow> filteredRows = new ArrayList<XSSFRow>();
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
XSSFRow row = (XSSFRow) rows.next ();
Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){
XSSFCell cell = (XSSFCell) cells.next ();
if (cell.toString().contains("Ginko")) {
filteredRows.add(row);
break;
}
}
}
You can check if a cell is in a specific column by calling cell.getColumnIndex() == columnNumber. For example:
for(Cell cell : row) {
if(cell.getColumnIndex() == 1) {
// process a cell in column 1
}
}
Source: https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getColumnIndex()

How to populate an Excel sheet with the data from an arraylist using Apache POI

How to populate an Excel sheet with the data from an arraylist using Apache POI?
public String exporttoexcel(UserDetails user) throws Exception {
System.out.print("Inside serviceimpl.ExportToExcel method");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
List<UserDetails> lstUserDetail = getUserDetailList();
for (int i=0; i<lstUserDetail.size(); i++) {
UserDetails lstUserDetail1 = lstUserDetail.get(i);
String a=lstUserDetail1.getStrUserName();
System.out.print("useridddd is"+a);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(lstUserDetail1.getStrUserId());
cell.setCellValue(lstUserDetail1.getStrUserName());
cell.setCellValue(lstUserDetail1.getStrEMail());
cell.setCellValue(lstUserDetail1.getStrUserStatus());
cell.setCellValue(lstUserDetail1.getStrUserRole());
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("file created");
return null;
}
You have created one single cell and entering all the values in a same single cell each time.
You need to take two loops. One for iterating through row and another for iterating through column. Though I have not tested... use code like below.
for(int RowNum=0; RowNum<MaxArrayLength;RowNum++){
HSSFRow row = sheet.createRow(RowNum);
for(int ColNum=0; ColNum<ArrayWidth;ColNum++){
HSSFCell cell = row.createCell(ColNum);
cell.setCellValue(ArrayList[RowNum][ColNum]);
}
}
FileOutputStream fileOut = new FileOutputStream("your file path");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet name");
try {
//creating the headers
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("name");
row.createCell(1).setCellValue("Name1");
row.createCell(2).setCellValue("name2");
//get the list which u want
List<String> list = getNamesList();
int rowNum = 1;
for (Name name : list ) {
Row row1 = sheet.createRow(rowNum++);
row1.createCell(0).setCellValue((name.get..));
}
workbook.write(fileOut);
}

Categories