I'm having a lot of problems with numeric formats in a Cell with POI.
I need to print in the cell 11 decimals for a number and also that the cell has a numeric format to make the sum when you select the data
And I have this code:
private void writeDecimal(HSSFRow row, Double data, int position) {
String pattern = "#.0000000000";
HSSFCell celda = row.createCell(position);
CellStyle styleDecimal = styles.get(ITEM_DECIMAL); // Font and alignment
styleDecimal.setDataFormat(libro.getCreationHelper().createDataFormat().getFormat(pattern));
celda.setCellStyle(styleDecimal);
celda.setCellType(Cell.CELL_TYPE_NUMERIC);
celda.setCellValue(data);
}
But the result always print less decimal because Excel rounds the number:
If I convert the Double to String, prints the 11 decimals but it doesn't make the sum if I select all the numbers.
Any idea how to resolve this?
Thanks
Open the xlsx file select the column , right click on cell -> Format cells...->custom->type = 0.00000000000 click ok.
now whatever you will write on that cell, it will print on that format and if you select also it will show the sum.
by code
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ChangeXlxsDataFormat {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Workbook wb = new HSSFWorkbook();
Sheet sheet = (Sheet) wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum);
cell = row.createCell(colNum);
style = wb.createCellStyle();
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.00000000000"));
cell.setCellStyle(style);
cell.setCellValue(5.12345678908);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(2.12345678908);
FileOutputStream fileOut = new FileOutputStream("test.xls");
wb.write(fileOut);
fileOut.close();
}
}
This code snippet doesn't contain celda.setCellStyle( styleDecimal ). Is it missing in the real code too? Add it.
Edit:
Here is a simple example using your function. It works well.
private static HSSFWorkbook workbook;
public static void main( String args[] ) throws IOException {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet( "sheet" );
HSSFRow row = sheet.createRow( 0 );
writeDecimal( row, 0.0781013, 0 );
FileOutputStream fos = new FileOutputStream( "workbook.xls", false );
workbook.write( fos );
fos.close();
}
private static void writeDecimal( HSSFRow row, Double data, int position ) {
String pattern = "#.0000000000";
HSSFCell celda = row.createCell(position);
CellStyle styleDecimal = workbook.createCellStyle(); // Font and alignment
styleDecimal.setDataFormat(workbook.createDataFormat().getFormat(pattern));
celda.setCellStyle(styleDecimal);
celda.setCellType(Cell.CELL_TYPE_NUMERIC);
celda.setCellValue(data);
}
What was the problem in your code? I don't know. Your style definitely wasn't applied to the page: zeros shouldn't be rendered with "#".
Related
Currently I'm using the format "#,##0.00" for all the Number type values retrieved from oracle DB to be saved in an excel file, but I don't want to save all values with a floating point if they don't have it on DB
For example
12 should be 12
12.1 should be 12.10
12.123 should be 12.12
If no special number format is set for the cell, then number format "General" is used. That will show 12 or 12.1 or 12.123. So to get what you want two different number formats ("0" (or "#,##0" if thousands separator shall be used) for integers and "#,##0.00" for decimals) are needed.
So main question is how to determine whether a number is integer or decimal. Following code does this task using the methods of Number. If number's integer value is equal to number's decimal value, then number is integer.
It creates a sheet showing 12 in A1, 12.10 in A2 and 12.12 in A3.
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.List;
import java.util.ArrayList;
public class CreateExcelDifferentNumberformats {
public static void main(String[] args) throws Exception {
//Workbook workbook = new HSSFWorkbook();
Workbook workbook = new XSSFWorkbook();
// Create CellStyles
DataFormat format = workbook.createDataFormat();
CellStyle integerCellStyle = workbook.createCellStyle();
//integerCellStyle.setDataFormat(format.getFormat("0"));
integerCellStyle.setDataFormat(format.getFormat("#,##0"));
CellStyle decimalCellStyle = workbook.createCellStyle();
decimalCellStyle.setDataFormat(format.getFormat("#,##0.00"));
Sheet sheet = workbook.createSheet();
List<Number> numbers = new ArrayList<Number>();
numbers.add(12); numbers.add(12.1); numbers.add(12.123);
int r = 0;
for (Number number : numbers) {
Row row = sheet.createRow(r++);
Cell cell = row.createCell(0);
cell.setCellValue(number.doubleValue());
if (number.intValue() == number.doubleValue()) {
cell.setCellStyle(integerCellStyle);
} else {
cell.setCellStyle(decimalCellStyle);
}
}
FileOutputStream out = null;
if (workbook instanceof HSSFWorkbook) {
out = new FileOutputStream("./CreateExcelDifferentNumberformats.xls");
} else if (workbook instanceof XSSFWorkbook) {
out = new FileOutputStream("./CreateExcelDifferentNumberformats.xlsx");
}
workbook.write(out);
out.close();
workbook.close();
}
}
I need to create an XL sheet using Apache POI with some values which are long numeric for ex:1234567891011.
When i use below sample code to generate the excel sheet, the data is stored in form of Scientific format (1.23457E+12). But i want to store this data as a number ex. 1234567891011.00 is fine.
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
String str = "1234567891011";
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(str);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
I tried to set the cell format to Numeric as below code but doesnt work.
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(str);
dateCell1.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
double converted = new Double(str);
dateCell1.setCellValue(converted);
Please tell if any way possible to do it.
Excel is using number format General per default. This switches to scientific format if needed. That means if cell width is too small or numeric value is too big.
So do using a cell style having a special number format 0.00 or 0.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelBigDecimal {
public static void main(String[] args) throws Exception {
//Workbook workbook = new XSSFWorkbook(); String filePath = "./Excel.xlsx";
Workbook workbook = new HSSFWorkbook(); String filePath = "./Excel.xls";
DataFormat format = workbook.createDataFormat();
CellStyle numberCellStyle = workbook.createCellStyle();
numberCellStyle.setDataFormat((short)8);
numberCellStyle.setDataFormat(format.getFormat("0.00"));
Sheet sheet = workbook.createSheet();
Cell cell = sheet.createRow(0).createCell(0);
double value = 1234567891011d;
cell.setCellValue(value);
cell.setCellStyle(numberCellStyle);
sheet.setColumnWidth(0, 20*256);
FileOutputStream out = new FileOutputStream(filePath);
workbook.write(out);
out.close();
workbook.close();
}
}
That leads to showing 1234567891011.00 in cell A1.
Leave the cell as String type and format your number java side.
long yourLongNumber = 1234567891011;
String strLong = String.format("%d", yourLongNumber);
//out: "1234567891011"
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
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.
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();
}
}