1
我使用apache poi创建excel表格。我有像 - 337499.939437217这样的数字,我想在没有四舍五入的情况下在excel中显示。单元格格式也应该是数字(对于某些列)和货币(对于某些列)。apache poi中的数字和单元格格式
请建议我应该使用哪个BuiltinFormat来实现此目的。
非常感谢您的帮助。
我使用apache poi创建excel表格。我有像 - 337499.939437217这样的数字,我想在没有四舍五入的情况下在excel中显示。单元格格式也应该是数字(对于某些列)和货币(对于某些列)。apache poi中的数字和单元格格式
请建议我应该使用哪个BuiltinFormat来实现此目的。
非常感谢您的帮助。
起初,您需要知道如何使用DataFormats。那么你需要知道guidelines for customizing a number format。
对于您的号码-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.456789);
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(123456789.);
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();
}
}