最近做一个项目要读取excel内容写入数据库, 当时拿到感觉easy但是做出来就郁闷了...因为excel的的单元格不是excel中定义的日期类型, 假如是日期类型通过下面的代码就可以判断了
//是不是数字
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
//判断单元格是日期类型的
if(HSSFDateUtil.isCellDateFormatted(cell))
{
System.out.println(cell.getDateCellValue());
}
else
{
System.out.printlm(cell.getNumericCellValue());
}
}
谁料不行...但是网上的大侠都说是可以判断的.于是我就判断这可能不是日期类型( 但是在excel看时是以日期的格式的 ), 我查看excel的单元格,,原来是自定义的..悲剧了..格式是#### / ## / ## 这个, 挣扎了一番..把代码写了出来..
Cell cell = row_val.getCell((short)col_val);
CellStyle cellStyle = cell.getCellStyle();
String val = "";
String dateF = "####\\/##\\/##";
if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
if(cellStyle.getDataFormatString().equals(dateF))
{
double d_temp = Double.valueOf(cell.toString());
Integer i_temp = (int)d_temp;
String S_temp = i_temp.toString();
String month = "";
if(S_temp.substring(4, 5).equals("0"))
{
month = S_temp.substring(5, 6);
}
else
{
month = S_temp.substring(4, 6);
}
val = S_temp.substring(6)+"-"+month+"月-"+S_temp.substring(0, 4);
}
else if(HSSFDateUtil.isCellDateFormatted(cell))
{
Date D_temp = cell.getDateCellValue();
val = D_temp.getDate()+"-"+(D_temp.getMonth()+1)+"月-"+(D_temp.getYear()+1900);
}
//把科学计算法去掉
else
{
Double d_temp = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat();
val = df.format(d_temp).replaceAll(",", "").toString();
}
}
else
{
val = row_val.getCell((short) col_val)
.getStringCellValue();
}