Apache POI How to change dataformat with conditional formatting

20,725

Solution 1

Cell new_cell = row.createCell(index_column_found);
XSSFCellStyle cs = wBook.createCellStyle();
XSSFDataFormat df = wBook.createDataFormat();
cs.setDataFormat(df.getFormat(cell_custom_format));
new_cell.setCellStyle(cs);

This work very well with POI 3.12

Solution 2

Here is the code that will satisfy your requirement:

FileOutputStream out = new FileOutputStream("dateFormat.xls");
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
HSSFCellStyle cs = hssfworkbook.createCellStyle();
HSSFDataFormat df = hssfworkbook.createDataFormat();
cs.setDataFormat(df.getFormat("#,##0.0"));

for(int i=0 ;i <100 ; i++ )
{
    double value = new Random(i).nextGaussian();
    HSSFRow row = sheet.createRow((short) i);
    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue(value);
    if(value>=0 && value<=1)
        cell.setCellStyle(cs);
}

hssfworkbook.write(out);
out.close();
Share:
20,725
JBerta93
Author by

JBerta93

I'm a young developer, i know Java SE and i use Java EE to develop a web application, however i know PHP(my first programming language)!I know also Posgresql and Mysql. I had some experience with C/C++ and ASM but my knowledge of this language are basic! I had develop some project with Arduino(using Wiring and C++) and Processing! For my last project i'm using HTML5 and JQuery!

Updated on August 09, 2020

Comments

  • JBerta93
    JBerta93 almost 4 years

    I'm an user of Apache POI and i make excel file (.xlsx) and i need to use the conditional formatting on a cell. My problem is this : i've a formula, if this formula returns a value that is between 0 and 1 i want show the result with one decimal at the contrary i want to show the result with any decimal. It is possible use the conditional formatting? If yes, how i can do it?