46

I need to display a value in an excel cell formatted like a percentage, e.g. like 12.3%.

By default the value is displayed as Text, but I need to display it as a number.

What is the appropriate method to achieve this?

nagireddy
  • 491
  • 2
  • 6
  • 6
  • 1
    @ax, this is a POI question, so it is a question of how to get POI to set the cell type as a percentage. – Yishai Oct 23 '09 at 13:53

2 Answers2

83

You need to:

  1. Set your data as number (floating-point), not as text.
  2. Specify cell format as percentage.

Something like:

cell.setCellValue(0.123); // set value as number
CellStyle style = workbook.createCellStyle();
style.setDataFormat(workbook.createDataFormat().getFormat("0.000%"));
cell.setCellStyle(style);

Take a look at user defined formats section of POI quick guide for more details. You may also want to go through the examples which show how to use different POI capabilities.

ChssPly76
  • 99,456
  • 24
  • 206
  • 195
5

POI has built-in formats check this link first

and check this link for example

For percentage, it will be something like this

dataCell.setCellValue(.12)
CellStyle stylePercentage = workbook.createCellStyle();
stylePercentage.setDataFormat(workbook.createDataFormat()
.getFormat(BuiltinFormats.getBuiltinFormat( 10 )));
 dataCell.setCellStyle(stylePercentage);
centic
  • 15,565
  • 9
  • 68
  • 125
Aasim ali
  • 318
  • 4
  • 6