我正在使用apache poi创建excel表.我有像 - 337499.939437217这样的数字,我想要显示它,因为它在excel中没有四舍五入.单元格格式也应该是数字(对于某些列)和货币(对于某些列).
请建议我应该使用哪种BuiltinFormats来实现这一目标.
非常感谢您的帮助.
Axe*_*ter 12
首先,您需要知道如何使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24906 次 |
| 最近记录: |