简体   繁体   中英

Apache POI data format

I am using Apache POI to build some excel files and I want to make sure some of the cells are of type "Number".

I tried the followings:

    style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
    cell.setCellValue(Integer.valueOf(value));
    cell.setCellStyle(style);

and

    HSSFDataFormat format = workbook.createDataFormat();
    style.setDataFormat(format.getFormat("0"));
    cell.setCellValue(Integer.valueOf(value));
    cell.setCellStyle(style);

where value is a String that I want to display in the cell as Number.

Both approaches work. So, is there a difference between HSSFDataFormat.getBuiltinFormat() and getFormat()?

As you can see in the sourcecode the function getFormat use the buildinFormats first:

public short getFormat( String format )
{
    ListIterator i;
    int ind;
    if (format.toUpperCase().equals("TEXT")) 
            format = "@";
      if ( !movedBuiltins )
      {
        i = builtinFormats.listIterator();
        while ( i.hasNext() )
        {
            ind = i.nextIndex();
            if ( formats.size() < ind + 1 )
            {
                formats.setSize( ind + 1 );
            }
            formats.set( ind, i.next() );
        }
        movedBuiltins = true;
    }
    i = formats.listIterator();
    while ( i.hasNext() )
    {
        ind = i.nextIndex();
        if ( format.equals( i.next() ) )
            return (short) ind;
    }
    ind = workbook.getFormat( format, true );
    if ( formats.size() <= ind )
        formats.setSize( ind + 1 );
    formats.set( ind, format );
    return (short) ind;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM