POI读取EXCEL中的日期

本文介绍了解析Excel中自定义日期格式(####/##/##)的方法,并提供了将该格式转换为标准日期格式的具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做一个项目要读取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();
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值