java to excel date formatting

15,497

Solution 1

Try this:

cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("MM/dd/yyyy hh:mm");

Solution 2

Try to define a static WritableCellFormat which takes care of the date formatting.

// Required classes.
import java.util.TimeZone;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.WritableCellFormat;

// Defined once.
public static final WritableCellFormat DATE_CELL_FRMT;
static {
    DateFormat df = new DateFormat("MM/dd/yyyy hh:mm");
    df.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"))
    DATE_CELL_FRMT = new WritableCellFormat(df);
}

// Usage
writableCell = new DateTime(sheetColumn, sheetRow, gmtDate, DATE_CELL_FRMT);
Share:
15,497
samligo
Author by

samligo

Updated on June 27, 2022

Comments

  • samligo
    samligo about 2 years

    The problem is when I'm running my application and have a grid (with strings and date columns) and save it as an excel file.

    When I save it for the first time everything is correctly formatted, but when I try to save the same exact grid again a second time, the date formatting is gone (it's just a float value that when i right click and format to a dateTime object works). When I restart my app it will work again for the first time, then lose formatting again

    the code looks like this:

    Calendar calendar = Calendar.getInstance();
    
    calendar.setTime((Date)data);
                Date gmtDate = new Date(((Date) data).getTime() + (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)));
    
    writableCell = new jxl.write.DateTime(sheetColumn, sheetRow, gmtDate, jxl.write.DateTime.GMT);
    
    cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("m/d/yyyy h:mm");
    
    writableCell.setCellFormat(cellFormat);
    
    sheet.addCell(writableCell);
    

    I kept break-pointing and everything is as it should be (it always knew it was a dateTime type before going in to the sheet), so I don't think it's from the code.

    Has anyone else run into this issue?

  • samligo
    samligo about 12 years
    I've tried that too unfortunately that gives me the same results