gpt4 book ai didi

apache-poi - apache poi 中的数字和单元格格式

转载 作者:行者123 更新时间:2023-12-02 20:24:37 27 4
gpt4 key购买 nike

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

请建议我应该使用哪种内置格式来实现此目的。

非常感谢您的帮助。

最佳答案

首先您需要知道如何使用 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.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();
}
}

关于apache-poi - apache poi 中的数字和单元格格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439591/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com