2015-12-08 150 views
1

我有一个excel文件,它有几个字符串数据类型列,一个数字列和一个日期列。我正在使用Apache POI来读取文件。 下面是我如何处理数据类型在Java中使用POI读取Excel

Cell cell = sheet.getRow(i).getCell(j); 

       if(cell!=null){ 
        switch(cell.getCellType()){ 
        case Cell.CELL_TYPE_STRING: 
         cellValue = cell.getStringCellValue(); 
         break; 
        case Cell.CELL_TYPE_NUMERIC: 
         DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
         Date cellDate = cell.getDateCellValue(); 
         cellValue = df.format(cellDate); 
         break;       
        case Cell.CELL_TYPE_BLANK: 
         break; 
        default : 
        }      
       } 

这正常工作与字符串和日期数据类型。但对于数字,它将该值转换为日期。我知道这是因为处理有问题。你可以请教如何适应数字和日期数据类型的处理?

谢谢, 山姆。

+1

为什么不直接使用[DataFormatter](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html)将单元格变成字符串,并让它处理你的复杂性? – Gagravarr

回答

2

如果你知道什么样的数据类型属于每个列,你甚至不必每次检查电池类型:

switch (columnIndex) { 
    case 0: 
    case 1: 
    case 2: { 
     cellValue = cell.getStringCellValue(); 
     break; 
    } 
    case 3: { 
     Date cellDate = cell.getDateCellValue(); 
     // ... 
     break; 
    } 
    case 4: { 
     cellValue = cell.getNumericCellValue(); 
     break; 
    }  
} 

如果列可以同时包含数字和日期,你可以试试这个

import org.apache.poi.ss.usermodel.DateUtil; 

case Cell.CELL_TYPE_NUMERIC: 
    if (DateUtil.isCellDateFormatted(cell)) { 
     // your code for date handling 
    } else { 
     cellValue = cell.getNumericCellValue(); 
    } 
+0

感谢Adam!工作就像一个魅力:) – Sam

相关问题