質問

I'm reading an Excel spreadsheet using JXL and Groovy like this:

WorkbookSettings settings = new WorkbookSettings();
settings.encoding = "Cp1252"
settings.locale = new Locale("pt", "BR")
Workbook workbook = Workbook.getWorkbook(is, settings)
Sheet sheet = workbook.getSheet(0)

And then I have a cell in Excel which value is 09/01/2013 (dd/mm/yyyy). But then, when I retrieve cell contents, JXL automatically does some conversion and gives this back at me:

"09/01/13" == sheet.getCell(col, line).contents?.trim()

But then, when I cast the Cell to a DateCell, the Date representation of "09/01/13" becomes Jan 8, 2013 (!):

DateCell dc = ((DateCell) sheet.getCell(col, line))
println "date from JXL: ${dc.date}" // prints Tue Jan 08 22:00:00 BRST 2013

Would anyone have any ideas about how to fix this? If I could just retrieve the actual cell contents directly (09/01/2013), then I could do all the conversion stuff by myself.

Thanks!

役に立ちましたか?

解決

From: http://www.andykhan.com/jexcelapi/tutorial.html#dates

When displaying dates, the java.util package automatically adjusts for the local timezone. This can cause problems when displaying dates within an application, as the dates look as if they are exactly one day previous to that which is stored in the Excel spreadsheet, although this is not in fact the case.

...

The easiest way to work around this (and the method used internally by the getContents() method of a jxl.DateCell) is to force the timezone of the date format as follows:

TimeZone gmtZone = TimeZone.getTimeZone("GMT");
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
format.setTimeZone(gmtZone);

DateCell dateCell = .... 
String dateString = format.format(dateCell.getDate());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top