Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache poi date format

Hi i am reading csv file and getting date in 01-01-2011 but i want it in 01-Jan-2011 format when i write .xlsx file using apache poi library. my code is

XSSFDataFormat df = workBook.createDataFormat();
cs.setDataFormat(df.getFormat("dd-MMM-yy"));

but it is not working for me. where am i doing mistake.

like image 559
Lalit Chattar Avatar asked Mar 18 '12 07:03

Lalit Chattar


People also ask

How do I change the date format in Apache POI?

To create date cell which display current date to the cell, we can use Apache POI's style feature to format the cell according to the date. The setDateformat() method is used to set date format.

How do I find cell type date in POI?

setREPO_DATE(row. getCell(16). getDateCellValue()); it works fine if cell is formatted as date in excel.

How do I format a date in Excel in Java?

Creating A Simple Date FormatString pattern = "yyyy-MM-dd" ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The specified parameter “pattern” is the pattern used for formatting and parsing dates.

How do I set cell value to date and apply default Excel date format?

In an Excel sheet, select the cells you want to format. Press Ctrl+1 to open the Format Cells dialog. On the Number tab, select Custom from the Category list and type the date format you want in the Type box. Click OK to save the changes.


1 Answers

Not only do you need to create a cell format, but you also need to apply it to the cell!

XSSFDataFormat df = workBook.createDataFormat();
cs.setDataFormat(df.getFormat("d-mmm-yy"));

// Get / Create our cell
XSSFRow row = sheet.createRow(2);
XSSFCell cell = row.createCell(3);

// Set it to be a date
Calendar c = Calendar.getInstance();
c.set(2012,3-1,18); // Don't forget months are 0 based on Calendar
cell.setCellValue( c.getTime() );

// Style it as a date
cell.setCellStyle(cs);

Secondly, you need to be aware that Java and Excel differ slightly in how they express Date formatting rules. You should open up a copy of Excel, format a sample cell how you want, then take a note of the formatting rules needed. In your case, you'd gone for a Java style upper case M, while in Excel it's lower case (see above)

like image 80
Gagravarr Avatar answered Oct 05 '22 11:10

Gagravarr