且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用POI API在Excel中显示百分比值

更新时间:2023-02-18 15:58:14

您需要:


  1. 将数据设置为数字(浮点数),而不是文本。

  2. 指定单元格格式为百分比。

类似于:

  cell.setCellValue(0.123); //将值设置为number 
CellStyle style = workbook.createCellStyle();
style.setDataFormat(workbook.createDataFormat()。getFormat(0.000%));
cell.setCellStyle(style);

查看用户定义的格式部分。您也可以浏览示例,该示例展示如何使用不同的POI功能。 / p>

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?

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.