Apache POI 中的数字和单元格格式化

22

我正在使用Apache POI创建Excel表格。我有像-337499.939437217这样的数字,我想在Excel中原样显示它们,而不是四舍五入。此外,单元格格式应为数字(对于某些列)和货币(对于某些列)。

请建议我使用哪个BuiltinFormats来实现此目的。

非常感谢您的帮助。

1个回答

38

首先您需要知道如何使用DataFormats。然后,您需要了解自定义数字格式的指南

对于您的数字-337499.939437217,如果要使用常规数字格式显示并进行四舍五入,则可以使用格式#.###############。其中,#表示仅在需要时(不是前导零和/或不是最后一个小数位为零)才显示数字-请参见指南。因此,整个格式意味着最多显示15个小数位(如果需要),但只显示所需数量。

对于货币,您应该真正使用内置数字格式来显示。因此,货币符号取决于Excel的区域设置。以下BuiltinFormats可与apache poi一起使用。使用内置数字格式,您只需要十六进制格式数字即可。

示例:

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

此外,微软的自定义数字格式审查指南可能会有所帮助。 - Ilya Serbis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接