`

【转】JXL获取Excel单元格的日期(DateCell.getDate)与实际填写日期相差8小时的解决方法

    博客分类:
  • Java
阅读更多
用JXL获取的时间总是比Excel单元格实际填写的时间早八小时,例如
单元格中日期为“2009-9-10″,getDate得到的日期是“Thu Sep 10 08:00:00 CST 2009″;
单元格中日期为“2009-9-10 16:00:00″,getDate 得到的日期便是“Fri Sep 11 00:00:00 CST 2009″;

这种问题产生的原因 是JXL按照GMT时间来解析Excel单元格的时间,它始终认为被解析的单元格填写的时间 为格林威治时间,然后我们在本地getDate的时候会将格林威治时间转成本地时间,因此会相差8小时。
详见:jxl.read.biff.DateRecord.java类
private static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");

1、首先在D盘建立一个xls表(tests.xls),在A1单元格随便填写一个日期,例如2010-4-11 0:00:00
2、测试类:
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
 
public class JXLTest {
	public static void main(String[] args) throws BiffException, IOException,ParseException {
		Workbook workBook = Workbook.getWorkbook(new File("D:\\test.xls"));
		Sheet sheet = workBook.getSheet(0);
		DateCell cell = (DateCell) sheet.getCell(0, 0);
		System.out.println("Get date by JXL:" + cell.getDate());
		System.out.println("After converting,we can get the time we had writed-->"+ convertDate4JXL(cell.getDate()));
	}
 
	/**
	 * JXL中通过DateCell.getDate()获取单元格中的时间为(实际填写日期+8小时),原因是JXL是按照GMT时区来解析XML。
	 * 本方法用于获取单元格中实际填写的日期! 例如单元格中日期为“2009-9-10”,getDate得到的日期便是“Thu Sep 10 08:00:00 CST 2009”;
	 * 单元格中日期为“2009-9-10 16:00:00”,getDate得到的日期便是“Fri Sep 11 00:00:00 CST 2009”
	 * @author XHY
	 * @param jxlDate 通过DateCell.getDate()获取的时间
	 * @return
	 * @throws ParseException
	 */
	public static java.util.Date convertDate4JXL(java.util.Date jxlDate) throws ParseException {
		if (jxlDate == null)
			return null;
		TimeZone gmt = TimeZone.getTimeZone("GMT");
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
		dateFormat.setTimeZone(gmt);
		String str = dateFormat.format(jxlDate);
		TimeZone local = TimeZone.getDefault();
		dateFormat.setTimeZone(local);
		return dateFormat.parse(str);
	}
}
分享到:
评论
2 楼 tsinglongwu 2012-05-07  
顶,解决了获取Date单元格的内容问题,原来要转换成
DateCell cell = (DateCell) sheet.getCell(0, 0);
谢了
1 楼 alexyao8 2012-03-28  
威武,今天刚遇到这个问题

相关推荐

Global site tag (gtag.js) - Google Analytics