简体   繁体   English

JExcelAPI - 将日期写入Excel工作表会忽略日,月和年

[英]JExcelAPI - writing date to Excel sheet ignores day, month and year

I try to generate some Excel sheets in Java application using JExcelAPI (v. 2.6.3) and can't generate date cells properly. 我尝试使用JExcelAPI(v.2.6.3)在Java应用程序中生成一些Excel工作表,并且无法正确生成日期单元格。 For example, for code: 例如,对于代码:

WritableWorkbook workbook = null;
    workbook = Workbook.createWorkbook(new File("C:\\tmp\\tests.xls"));
    try {
        Date date = new Date();
        final WritableSheet sheet = workbook.createSheet("Sheet", 0);
        DateTime dateTime = new DateTime(0, 0, date);
        sheet.addCell(dateTime);
        System.out.println("Date1 is " + date);
        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2007);
        cal.set(Calendar.MONTH, Calendar.OCTOBER);
        cal.set(Calendar.DAY_OF_MONTH, 17);
        cal.set(Calendar.HOUR_OF_DAY, 8);
        cal.set(Calendar.MINUTE, 15);
        date = cal.getTime();
        dateTime = new DateTime(0, 1, date);
        sheet.addCell(dateTime);
        System.out.println("My birthday is on " + date);
    } finally {
        workbook.write();
        workbook.close();
    }

The output (on console) is: 输出(在控制台上)是:
Date1 is Mon Jun 08 11:14:45 GMT+01:00 2009 Date1是星期一08月11日11:14:45 GMT + 01:00 2009
My birthday is on Wed Oct 17 08:15:45 GMT+01:00 2007 我的生日是10月17日星期三08:15:45 GMT + 01:00 2007

And in Excel file the cells are 在Excel文件中,单元格是
1900-01-00 10:14:46 1900-01-00 10:14:46
1900-01-00 07:15:46 1900-01-00 07:15:46

The time part in Excel is corrected to UTC and the date part is discarded. Excel中的时间部分更正为UTC,并丢弃日期部分。 While the reference mentions time zone problem, it says nothing about discarding dates. 虽然参考文献提到了时区问题,但它没有提到丢弃日期。 What am I doing wrong? 我究竟做错了什么?

OK. 好。 I figured it. 我想通了。 Creating DateFormat 创建DateFormat

DateFormat customDateFormat = new DateFormat ("dd MMM yyyy hh:mm:ss");
WritableCellFormat dateFormat = new WritableCellFormat (customDateFormat); 

and passing it to DateTime constructor 并将其传递给DateTime构造函数

DateTime dateTime = new DateTime(0, 0, date, dateFormat);

fixes it. 解决它。 It seems that by default only time part is taken. 似乎默认只采用时间部分。 Sorry for my dumbness. 对不起我的傻瓜。

POI is not the answer I'd recommend. POI不是我推荐的答案。 JExcel can manage it. JExcel可以管理它。 I don't see where you've set the type on that cell. 我没有看到你在那个单元格上设置类型的位置。 Have a look at DateFormats . 看看DateFormats

The problem is the same if you're using Excel. 如果您使用的是Excel,问题也是一样的。 If you enter a Date into a cell that doesn't have that format set you'll have unexpected behavior. 如果在没有设置该格式的单元格中输入日期,则会出现意外行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM