0

嗨,我正在用特定格式解析 Excel 中的单元格,其数据格式字符串为“$”#,##0 我想在该单元格中获取值但无法这样做,有人可以帮忙吗?

目前使用此代码,我得到的值为空白,但在 excel 中,该值为例如 40 美元。

 for (Row row : sheet) 
        {     
                Cell dataCell = row.getCell(colIndex); 

                if(dataCell!=null )
                {
                   if( row.getRowNum()==5)
                   {

                       System.out.println("Cell Value is::"+dataCell.toString());
                   }


                }

            }
4

3 回答 3

1

You seem to want the string to be magically formatted to look the same as in Excel, without any coding on your part. You can do that in POI, but that isn't the normal usecase. People normally want to get the values as numbers, booleans etc, and process them themselves.

The class you're looking for is DataFormatter. Your code would be something like

 DataFormatter fmt = new DataFormatter();
 for (Row r : sheet) {
    for (Cell c : r) {
       CellReference cr = new CellRefence(c);
       System.out.println("Cell " + cr.formatAsString() + " is " + 
                          fmt.formatCellValue(c) );
    }
 }
于 2012-07-26T20:18:45.527 回答
0

使用此方法获取单元格中的值。它可以帮助您

private String getCellValue(Cell cell) {
    if (cell == null) {
        return null;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
        return cell.getStringCellValue();
    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        return cell.getNumericCellValue() + "";
    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return cell.getBooleanCellValue() + "";
    }else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
        return cell.getStringCellValue();
    }else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
        return cell.getErrorCellValue() + "";
    } 
    else {
        return null;
    }
}
于 2012-08-22T06:45:25.087 回答
0

您必须根据数据类型获取值,而不仅仅是“字符串类型”。

HSSF 示例:

HSSFCell cell = poiFilaActual.getCell(intColActual);
if (cell != null) {
    if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
        return cell.getRichStringCellValue().toString();
    }  else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
        return new String( (cell.getBooleanCellValue() == true ? "true" : "false") );
    } else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
        return "";
    } else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
        if(HSSFDateUtil.isCellDateFormatted(cell)){
            return ( new SimpleDateFormat("dd/MM/yyyy").format(cell.getDateCellValue()) );
        }else{
            return new BigDecimal(cell.getNumericCellValue()).toString();
        }
    }
}
于 2012-07-26T19:32:32.213 回答