Excel Apache POI is printing only last element while performing setCellValue() - java

I am reading some data from excel and writing it to another sheet in the same file in the form of column and I want the column to be printed in the row. When I am performing iteration createRow().setCellValue() is printing only last element.
package com.editDistance;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadColumnsEditDistance {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File src = new File("C:\\Users\\xyz\\Desktop\\folder\\file.xlsx");
FileInputStream file = new FileInputStream(src);
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet1 = workbook.getSheetAt(0);
int rows = sheet1.getPhysicalNumberOfRows();
workbook.createSheet();
Sheet sheet2 = workbook.getSheetAt(1);
for (int Readingrowindex = 1; Readingrowindex < rows; Readingrowindex++) {
String ah = sheet1.getRow(Readingrowindex).getCell(1).getStringCellValue();
sheet2.createRow(Readingrowindex).createCell(0).setCellValue(ah);
sheet2.createRow(0).createCell(Readingrowindex).setCellValue(ah);
}
FileOutputStream fout = new FileOutputStream(src);
workbook.write(fout);
}
}

Do you want to create sheet with the same cells in first column and first row, like a named table? If yes, you need modify your code, because you always rewrite first row, that's why you get only last item. Do this:
File src = new File("C:\\Users\\xyz\\Desktop\\folder\\file.xlsx");
FileInputStream file = new FileInputStream(src);
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet1 = workbook.getSheetAt(0);
int rows = sheet1.getPhysicalNumberOfRows();
workbook.createSheet();
Sheet sheet2 = workbook.getSheetAt(1);
Row sheet2FirstRow = sheet2.createRow(0);
for (int Readingrowindex = 1; Readingrowindex < rows; Readingrowindex++) {
String ah = sheet1.getRow(Readingrowindex).getCell(1).getStringCellValue();
sheet2.createRow(Readingrowindex).createCell(0).setCellValue(ah);
Cell cell = sheet2FirstRow.createCell(Readingrowindex);
cell.setCellValue((String) ah);
}
FileOutputStream fout = new FileOutputStream(src);
workbook.write(fout);

I think it's because you keep creating row 0 over and over again so it's overwriting what you already created.
You probably want to do something like this:
if(sheet2.getRow() == null){
sheet2.createRow(0).createCell(Readingrowindex).setCellValue(ah);
}else{
sheet2.getRow(0).createCell(Readingrowindex).setCellValue(ah);
}

I faced the similar problem while writing to the code (it was printing the last row only).
Here is the solution for my code:
Failed solution (printing only last cell) i.e. "Hello3"
sheet.createRow(8).createCell(0).setCellValue("Hello1");
sheet.createRow(8).createCell(1).setCellValue("Hello2");
sheet.createRow(8).createCell(2).setCellValue("Hello3");
Working solution (Printing all the data) :
XSSFRow row;
row = sheet.createRow(8);
row.createCell(0).setCellValue("India 123");
row.createCell(1).setCellValue("India 234");
row.createCell(2).setCellValue("India 3453");
row = sheet.createRow(9);
row.createCell(0).setCellValue("Test 123");
row.createCell(1).setCellValue("Test 234");
row.createCell(2).setCellValue("Test 3453");

Related

POI Excel Selenium Decimal to text

I have data in Excel but when I run the code output in decimal but my excel cell format in Text
1.23456789E8
28.5
Also, how do I select radio button base on test data from excel sheet means select female button if cell data is female.
Also how to select data from the drop-down menu.
Attached image with Link for Excel file
//ReadExcelShe
package excelpoi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelShe {
public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException {
//Create a object of File class to open xlsx file
File file = new File(filePath+"\\"+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(inputStream);
Sheet she = wb.getSheet(sheetName);
return she;
}
}
// googletestppo
package testpoi;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import excelpoi.ReadExcelShe;
public class googletestppo {
// TODO Auto-generated method stub
WebDriver driver;
#Test(dataProvider = "testdata")
public void login(String firstn, String lastn, String usern, String passw, String regusern, String password, String month, String day, String year) throws InterruptedException {
driver = new ChromeDriver();
driver.get("http://facebook.com/");
driver.findElement(By.name("firstname")).sendKeys(firstn);
///amidfdsds
driver.findElement(By.name("firstname")).sendKeys(lastn);
///sfasfasbad
driver.findElement(By.name("reg_email__")).sendKeys(usern);
//dsasfzxv#gmail.com
driver.findElement(By.name("reg_email_confirmation__")).sendKeys(regusern);
//dsasfzxv#gmail.com
driver.findElement(By.name("reg_passwd__")).sendKeys(password);
//1234567890 // this output come in decimal
WebElement maleRadioBtn = driver.findElement(By.id("u_0_a"));
maleRadioBtn.click();
WebElement femaleRadioBtn = driver.findElement(By.id("u_0_9"));
femaleRadioBtn.click();
Select dropdown = new Select(driver.findElement(By.id("month")));
dropdown.selectByVisibleText(month);
//Oct
Select dropdown1 = new Select(driver.findElement(By.id("day")));
dropdown1.selectByVisibleText(day);
//29 this come in decimal
Select dropdown2 = new Select(driver.findElement(By.id("year")));
dropdown2.selectByVisibleText(year);
// 1985 this come in decimal
driver.findElement(By.name("websubmit")).click();
}
#DataProvider(name = "testdata")
public String[][] readExcel() throws IOException {
ReadExcelShe file = new ReadExcelShe();
org.apache.poi.ss.usermodel.Sheet she = file.readExcel(System.getProperty("user.dir") + "\\", "DDF.xlsx", "Sheet2");
int rowCount = she.getLastRowNum();
int columnCount = she.getRow(0).getPhysicalNumberOfCells();
String[][] inputdata = new String[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
Row row = she.getRow(i + 1);
for (int j = 0; j < columnCount; j++) {
inputdata[i][j] = row.getCell(j).toString();
System.out.println(inputdata[i][j]);
}
}
return inputdata;
}
}
I have data in Excel but when I run the code output in decimal but my excel cell format in >Text
1.23456789E8
28.5
See following post Always show two decimal points in excel cells using Apache poi
and official document: Busy Developers' Guide to HSSF and XSSF Features
You can indicate decimal format with DataFormat class. If you want to specify decimal format, then input set format as "#,##0.0000". Else please input format as "text".
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
int rowNum = 0;
int colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
wb.close();
For Excel drop down list, see the post Excel Drop down list using Apache POI

Apache POI sets Values in Cells of an xlsx file, but doesnt confirm them in the processing strip

I'm trying to write values into a xlsx file using java and POI.
It's nearly working as I want, but i have the following Problem:
The Values that my programm writes into the xlsx file are displayed there, but excel doesn't use my VLOOKUP and displays #N/A untill I go into the
processing strip and press Enter, then it works..
Here is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class XLSXEditor {
public XLSXEditor(){
}
public void xlsxWriter(String path, String uName, Date date/*, String timeF, String timeT*/) throws FileNotFoundException, IOException{
File excel = new File(path);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(1);
int r = getNonBlankRowCount(path);
XSSFRow row = sheet.getRow(r);
//Datum Style
CellStyle csDate = book.createCellStyle();
CreationHelper createHelper = book.getCreationHelper();
csDate.setDataFormat(createHelper.createDataFormat().getFormat("dd.mm.yyyy"));
csDate.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csDate.setBorderTop(XSSFCellStyle.BORDER_THIN);
csDate.setBorderLeft(XSSFCellStyle.BORDER_THIN);
csDate.setBorderRight(XSSFCellStyle.BORDER_THIN);
csDate.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
csDate.setFillPattern(CellStyle.SOLID_FOREGROUND);
//uname style
CellStyle csUname = book.createCellStyle();
csUname.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csUname.setBorderTop(XSSFCellStyle.BORDER_THIN);
csUname.setBorderLeft(XSSFCellStyle.BORDER_THIN);
csUname.setBorderRight(XSSFCellStyle.BORDER_THIN);
csUname.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
csUname.setFillPattern(CellStyle.SOLID_FOREGROUND);
//fill username column in xlsx file
XSSFCell celluName = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
while(celluName != null){
r++;
row = sheet.createRow(r);
celluName = row.createCell(0);
}
if(celluName == null){
celluName = sheet.getRow(r).createCell(0);
celluName.setCellStyle(csUname);
}
celluName.setCellValue(uName);
//fill date column in xlsx file
XSSFCell cellDate = row.getCell(5, Row.RETURN_BLANK_AS_NULL);
while(cellDate != null){
r++;
row = sheet.createRow(r);
cellDate = row.getCell(5);
}
if(cellDate == null){
cellDate = sheet.getRow(r).createCell(5);
cellDate.setCellValue(date);
cellDate.setCellStyle(csDate);
}
//fill PNr column in xlsx file
int r1 = r+1;
XSSFCell cellPNr = row.getCell(1, Row.RETURN_BLANK_AS_NULL);
cellPNr = sheet.getRow(r).createCell(1);
cellPNr.setCellValue("=SVERWEIS(A"+r1+";'MA Stamm'!$A$2:$E$98;2;FALSCH)");
FileOutputStream fos = new FileOutputStream(path);
book.write(fos);
fos.flush();
fos.close();
}
public int getNonBlankRowCount(String path) throws IOException{
File excel = new File(path);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(1);
int rowCount = 0;
int index = book.getSheetIndex(sheet);
if(index==-1){
rowCount=-1;
return rowCount;
}
else{
sheet=book.getSheetAt(index);
Iterator<Row> rowIterator = sheet.rowIterator();
rowCount=0;
while(rowIterator.hasNext()){
Row row = (Row) rowIterator.next();
XSSFCell cell =(XSSFCell) row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell == null){
break;
}
rowCount++;
}
return rowCount;
}
}
}
Formula cell content is fundamentally different from text cell content in Excel. Your code line:
cellPNr.setCellValue("=SVERWEIS(A"+r1+";'MA Stamm'!$A$2:$E$98;2;FALSCH)");
sets a string cell value instead of a formula. Do using Cell.setCellFormula instead to set formula cell content.
And since Excel stores only formulas in English_US notation in its files you need using English_US notation of the formula:
cellPNr.setCellFormula("VLOOKUP(A"+r1+",'MA Stamm'!$A$2:$E$98,2,FALSE)");
English_US notation means English function names (for ex. VLOOKUP instead of SVERWEIS), English constant names (for ex. FALSE instead of FALSCH), comma as parameter delimiter (for ex. VLOOKUP(A1,F1:G100,2,FALSE) instead of VLOOKUP(A1;F1:G100;2;FALSE)) and dot as decimal delimiter in floating point literals (for ex. SUM(1.23, 3.45, 4) instead of SUMME(1,23; 3,45; 4).
The localization is made in the localized Excel GUI versions after opening the file.
And then you need some kind of Formula Recalculation. Simplest way is by delegating re-calculation to Excel by setting:
book.setForceFormulaRecalculation(true);
before writing out the book.

Printing entire Excel Workbook in java without opening the excel document

How do I print an excel Workbook without having it open in the background, using Java?
Please note that I need to print all the sheets, not just the active one.
I have tried things like Desktop.print(FileName); but that doesn't seem to work for all the sheets.
I am using the Apache POI API to create Excel files through Java.
Many thanks!
UPDATE
To explain my problem a little more, I am using Apace POI to print the Excel file as -
HSSFSheet sheet = workbook.getSheet("Sheet5");
HSSFRow row21 = sheet.getRow((short)5);
row21.getCell((short)2).setCellValue(notcorrect);
desktop.print(new File(filename));
HSSFSheet sheet7 = workbook.getSheet("Sheet7");
HSSFRow row20 = sheet7.getRow((short)3);
row20.getCell((short)2).setCellValue(logreference);
row20.getCell((short)4).setCellValue(ISSUENUMBER);
desktop.print(new File(filename));
HSSFSheet sheet8 = workbook.getSheet("Sheet8");
HSSFRow row22 = sheet8.getRow((short)3);
row22.getCell((short)2).setCellValue(logreference);
row22.getCell((short)4).setCellValue(ISSUENUMBER);
desktop.print(new File(filename));
But this seems to work only for the active workbook. If I have a workbook in my Excel file as the following -
The code above will only print the active sheet i.e. sheet # 5. How do I use Jexcel to print Sheet 5, 6 AND 7?
Many thanks!
Before writing code we have to download apache-poi jars
https://poi.apache.org/download.html
Download - poi-bin-5.0.0-20210120.tar.gz (current version)
package test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class P1 {
public static void main(String[] args) throws IOException {
//Path to excel from system = /Users/user/Downloads/test1.xlsx"
File f = new File("/Users/user/Downloads/test1.xlsx");
FileInputStream fis = new FileInputStream(f);
XSSFWorkbook wb = new XSSFWorkbook(fis);
//June2021 is my sheet name of excel
XSSFSheet sheet = wb.getSheet("June2021");
int RowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
for(int i=0; i<= RowCount; i++) {
System.out.print("Row "+ i + " data is : ");
int cellCount = sheet.getRow(i).getLastCellNum();
for(int j=0; j<cellCount; j++) {
XSSFCell c1 = sheet.getRow(i).getCell(j);
System.out.print(c1 + " ");
}
System.out.println();
}
}
}

Using Apache POI to get/modify cell values in one or more Excel sheets

I have a small application written in Java which uses Apache POI to read/modify values in an Excel document. I'm referencing cells using sheet name, like for cell A1 in sheet "Sheet1", I use "Sheet1!A1".
The application runs from the command line with three arguments: the document name, the cells with values I want to replace, the cells from where I want to get the output.
Example: ReadExcel test.xls Sheet1!B2=10;Sheet1!B3=20 Sheet1!B7
The above example works fine.
The problem is when I want to modifiy cells or get the output from another sheet.
Example: ReadExcel test.xls Sheet1!B2=10;Sheet1!B3=20 Sheet2!B2
My code is bellow:
package poitest;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
public class ReadExcel {
public static void main(String[] args) throws FileNotFoundException, IOException {
// Will contain cell name / value pair for input cells
Map<String, String> inputCellsMap = new HashMap<String, String>();
// Will contain cell name for output cells
List<String> outputCells = new ArrayList<String>();
// Open the Excel file
FileInputStream file = new FileInputStream(new File(args[0]));
// Get the current workbook
HSSFWorkbook workbook = new HSSFWorkbook(file);
// Get the first sheet of the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
// Get the input cells that need to be modified and
// store their name and value in the inputCellsMap
for (String element : args[1].split(";")) {
inputCellsMap.put(element.split("=")[0], element.split("=")[1]);
}
// Get the output cells that will be accessed for resulting values
for (String element : args[2].split(";")) {
outputCells.add(element);
}
// Loop through the cells that need to be modified and
// set the new value in the Excel document
Iterator<Entry<String,String>> inputIterator = inputCellsMap.entrySet().iterator();
while (inputIterator.hasNext()) {
Map.Entry<String,String> inputEntry = (Map.Entry<String,String>) inputIterator.next();
CellReference cellReferenceInput = new CellReference(inputEntry.getKey());
int cellReferenceInputRow = cellReferenceInput.getRow();
int cellReferenceInputColumn = cellReferenceInput.getCol();
Row rowInput = sheet.getRow(cellReferenceInputRow);
if (rowInput == null)
rowInput = sheet.createRow(cellReferenceInputRow);
Cell cellInput = rowInput.getCell(cellReferenceInputColumn, Row.CREATE_NULL_AS_BLANK);
cellInput.setCellValue(Integer.parseInt(inputEntry.getValue()));
}
// Apply all formulas after altering cell values
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
// Get the results from the output cells
for (int i = 0; i < outputCells.size(); i++) {
CellReference cellReferenceOutput = new CellReference(outputCells.get(i));
int cellReferenceOutputRow = cellReferenceOutput.getRow();
int cellReferenceOutputColumn = cellReferenceOutput.getCol();
Row rowOutput = sheet.getRow(cellReferenceOutputRow);
Cell cellOutput = rowOutput.getCell(cellReferenceOutputColumn, Row.CREATE_NULL_AS_BLANK);
// Display results
System.out.println(cellOutput.getNumericCellValue());
}
workbook.close();
}
}
If you look at the longest constructor of CellReference, you'd notice that a reference consists of 5 properties:
String sheetName (can be null)
int row
int col
boolean rowAbsolute
boolean colAbsolute
Your command-line arguments include the sheet name, but you're not using it.
First, remove the following line from your code: HSSFSheet sheet = workbook.getSheetAt(0);
Instead, you'll need to lookup the sheet by name using getSheet(String), right after you create the CellReference:
HSSFSheet sheet = workbook.getSheet(cellReferenceInput.getSheetName());
HSSFSheet sheet = workbook.getSheet(cellReferenceOutput.getSheetName());

exporting tables to excel / word using POI

I want the code to export tables / reports to Excel and Word using POI.
I saw the examples that came with POI but could not understand. Can anyone provide me a small/easy code to do the same.
Seeing as you wanted actual code for using POI. Here is some to do some exporting:
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
public class XLSExporter implements Exporter {
/**
* Constructor for XLSExporter
*/
public XLSExporter(){
}
public void exportFile( File f, List o ) throws IOException{
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(f);
HSSFSheet sheet = wb.createSheet();
ListIterator it = o.listIterator();
//Construct the headings
HSSFRow headingsRow = sheet.createRow((short)0);
//Heading format
HSSFFont headingFont = wb.createFont();
headingFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headingStyle = wb.createCellStyle();
headingStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headingStyle.setFont(headingFont);
HSSFCell headingA = headingsRow.createCell((short)0);
headingA.setCellValue("Heading");
headingA.setCellStyle(headingStyle);
int i = 1;
// Iterate over the rows
while(it.hasNext()){
//Create the row
HSSFRow row = sheet.createRow((short)i);
//Write data
HSSFCell cellRunway = row.createCell((short)0);
cellRunway.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellRunway.setCellValue("Whateva");
cellRunway.setCellStyle(standardStyle);
i++;
}
//Set the column widths where needed
sheet.setColumnWidth((short)1, (short)4000);
wb.write(fileOut); // Write the workbook
fileOut.close();
}
}

Categories