POI:如何获取格式化单元格的正确单元格类型

时间:2015-09-14 09:36:25

标签: java apache-poi

我在excel中有一个格式化的单元格为 dd-mm-yyyy hh:mm:ss 。(右键单击单元格>选择格式单元格>选择自定义并选择提到的格式)我正在尝试使用cell.getCellType()获取此单元格的单元格类型,我将其作为String获取。对于格式为Number的单元格,这类似。是否可以将excel中格式化单元格的单元格类型设置为Cell.CELL_TYPE_NUMERIC,如dd-mm-yyyy hh:mm:ss使用Apache POI?或者我如何格式化单元格以便我可以将单元格类型设置为Cell.CELL_TYPE_NUMERIC。

使用jxl时,我将该Cell的CellType作为DateFormulae。

编辑: 下面是我正在使用的代码。在单元格中,我们发送Date值,该值在POI中被视为数字单元格类型。但它将该值视为String。

private void copyCell(Cell cell,Row row,int targetRow,Sheet sheet){

framework

编辑2: @ Gagravarr- Reading date value from excel cell as a String没有解决我的问题。 我的查询是::基于单元格的cellType我必须执行一些操作。但是当我正在读取日期或数字单元格时,我将cellType作为字符串。因为我将cellType作为字符串获取我不在应用我需要申请日期或数字操作的职位。

比如说:如果我的单元格是Date类型,那么我将该单元格的值设置为今天的日期。我试图在String Cell Type中执行以下操作:

如果(DateUtil.isCellDateFormatted(小区)){

    // Copy style from old cell and apply to new cell
    CellStyle newCellStyle = newWorkbook.createCellStyle();
    newCellStyle.cloneStyleFrom(cell.getCellStyle()); 

    // If there is a cell comment, copy
    if(cell==null){
        newCell.setCellValue("");
        return;
    }
    if (cell.getCellComment() != null) newCell.setCellComment(cell.getCellComment());

    // If there is a cell hyperlink, copy
    if (cell.getHyperlink() != null) {newCell.setHyperlink(cell.getHyperlink()); 
    }
    // Set the cell data type
    newCell.setCellType(cell.getCellType());

    // Set the cell data value

    switch (cell.getCellType())
    {
    case Cell.CELL_TYPE_BLANK:
        newCell.setCellValue(cell.getStringCellValue());
        newCell.setCellStyle(newCellStyle);
        newCell.setCellType(3);
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        newCell.setCellValue(cell.getBooleanCellValue());
        newCell.setCellStyle(newCellStyle);
        newCell.setCellType(4);
        break;
    case Cell.CELL_TYPE_ERROR:
        newCell.setCellErrorValue(cell.getErrorCellValue());
        newCell.setCellStyle(newCellStyle);
        newCell.setCellType(5);
        break;

    case Cell.CELL_TYPE_NUMERIC:
        if(DateUtil.isCellDateFormatted(cell)){
            newCell.setCellValue(cell.getDateCellValue());
        }else{
            DataFormatter dataFormatter=new DataFormatter();
            Format format=dataFormatter.getDefaultFormat(cell);
            dataFormatter.setDefaultNumberFormat(format);

            newCell.setCellValue(dataFormatter.formatCellValue(newCell)); 
        }
        newCell.setCellType(0);
        break;
    case Cell.CELL_TYPE_STRING:
        if(DateUtil.isCellDateFormatted(cell)){

        }
        newCell.setCellValue(cell.getStringCellValue());


        newCell.setCellStyle(newCellStyle);
        newCell.setCellType(1);
        break;

    }

}

但我收到错误:无法从文本单元格中获取数值。 在此先感谢。

0 个答案:

没有答案
相关问题