簡體   English   中英

Apache POI單元格格式化

[英]Apache poi cell formatting

我正在嘗試使用Apache poi dataformatter將數字2852196格式化為$ 2,852,196。

NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
dataFormatter.addFormat("($#,##0_);($#,##0)", numberFormat);
//after adding the above format, i see this format @ index 0, so i have taken 0 in the next line  

String formatCellValue = dataFormatter.formatRawCellContents((Long) cols.get(jj).getValue(), 0, "($#,##0_);($#,##0)");

但是產出是2,852,196美元。 我缺少某些東西或使用了不正確的方法。

- 謝謝。

此方法更改列數組中的所有元素

您將致電:

protected final static int TYPE_PORCENTAJE = 3;

setTypeColumn(sheet, Arrays.asList(19, 20, 21), TYPE_PORCENTAJE, null);


protected void setTypeColumn(Sheet sheet, List<Integer> columns, int type, Integer format) {
    CellType cellType = CellType.STRING;
    CellStyle style = sheet.getWorkbook().createCellStyle();
    CreationHelper createHelper = sheet.getWorkbook().getCreationHelper();

    switch (type) {
    case TYPE_NUMBER:
        style.setDataFormat(sheet.getWorkbook().createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(1)));
        break;
    case TYPE_MONEY:
        style.setDataFormat(
                sheet.getWorkbook().createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(format)));
        break;
    case TYPE_DATE:
        style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));
        break;
    case TYPE_PORCENTAJE:
        style.setDataFormat(sheet.getWorkbook().createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(0xa)));
        break;
    case TYPE_CUSTOM:
        style.setDataFormat(
                sheet.getWorkbook().createDataFormat().getFormat(BuiltinFormats.getBuiltinFormat(format)));
        break;
    case TYPE_TEXT:
        style.setDataFormat((short) BuiltinFormats.getBuiltinFormat("text"));
        break;
    default:
        break;
    }
    cellType = CellType.NUMERIC;
    final int lastRow = sheet.getLastRowNum();
    for (int i = 1; i <= lastRow; i++) {
        for (int j = 0; j < columns.size(); j++) {
            Cell cell = sheet.getRow(i).getCell(columns.get(j));
            String value = null;
            if (type == TYPE_TEXT) {
                value = cell.getStringCellValue();
            }
            cell.setCellType(cellType);
            cell.setCellStyle(style);
            if (type == TYPE_PORCENTAJE) {
                cell.setCellValue(cell.getNumericCellValue() / 100);
            }
            if (type == TYPE_TEXT) {
                style.setWrapText(true);
                cell.setCellStyle(style);
                cell.setCellValue(value);
            }
        }
    }
}

對於參數格式,請檢查此鏈接https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM