Number and cell Formatting in apache poi

空扰寡人 提交于 2019-12-06 02:39:58

问题


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:


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();
 }
}


来源:https://stackoverflow.com/questions/41439591/number-and-cell-formatting-in-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!