16
votes

I am creating excel sheet using apache poi. I have numbers like - 337499.939437217, which I want to show as it is in excel without rounding off. Also the cell format should be number (for some columns) and currency (for some columns).

Please suggest which BuiltinFormats should I use to achieve this.

Many thanks for the help.

1

1 Answers

28
votes

At first you need to know how to use DataFormats. Then you need to know the guidelines for customizing a number format.

For your number -337499.939437217 which will be displayed rounded with general number format, you could use format #.###############. The # means a digit which will be displayed only if needed (is not leading zero and/or is not zero as last decimal digit) - see guidelines. So the whole format means show up to 15 decimal digits if needed but only as much as needed.

For currency you should really using a built in number format for currency. So the currency symbol depends on the locale settings of Excel. The following BuiltinFormats are usable with apache poi. Using a built in number format you need only the hexadecimal format numbers.

Example:

import java.io.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateNumberFormats {

 public static void main(String[] args) throws Exception {
  Workbook wb = new XSSFWorkbook();

  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);
  cell.setCellValue(-337499.939437217); // general format

  style = wb.createCellStyle();
  style.setDataFormat(format.getFormat("#.###############")); // custom number format
  row = sheet.createRow(rowNum++);
  cell = row.createCell(colNum);
  cell.setCellValue(-337499.939437217);
  cell.setCellStyle(style);
  row = sheet.createRow(rowNum++);
  cell = row.createCell(colNum);
  cell.setCellValue(123.456789012345);
  cell.setCellStyle(style);
  row = sheet.createRow(rowNum++);
  cell = row.createCell(colNum);
  cell.setCellValue(123456789.012345);
  cell.setCellStyle(style);

  style = wb.createCellStyle();
  style.setDataFormat((short)0x7); // builtin currency format
  row = sheet.createRow(rowNum++);
  cell = row.createCell(colNum);
  cell.setCellValue(-1234.5678);
  cell.setCellStyle(style);

  sheet.autoSizeColumn(0);

  FileOutputStream fileOut = new FileOutputStream("CreateNumberFormats.xlsx");
  wb.write(fileOut);
  fileOut.close();
  wb.close();
 }
}