Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display percentage values in Excel using POI API

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?

like image 712
nagireddy Avatar asked Oct 23 '09 12:10

nagireddy


People also ask

What is POI API?

Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java programs. It is an open source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program.

What is Apache POI in Excel?

Apache POI is a 100% open source library provided by Apache Software Foundation. Most of the small and medium scale application developers depend heavily on Apache POI (HSSF + XSSF). It supports all the basic features of Excel libraries; however, rendering and text extraction are its main features.


2 Answers

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.

like image 200
ChssPly76 Avatar answered Sep 21 '22 22:09

ChssPly76


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); 
like image 39
Aasim ali Avatar answered Sep 24 '22 22:09

Aasim ali