开发者

How can i apply a dateformat style to one column in Excel with POI-3.2-FINAL?

开发者 https://www.devze.com 2022-12-24 19:40 出处:网络
I have to create an excel file with POI-3.2-Final (can\'t upgrade to 3.5+, for retro compatibility issues) and for each row, i have to format a date in col A.

I have to create an excel file with POI-3.2-Final (can't upgrade to 3.5+, for retro compatibility issues) and for each row, i have to format a date in col A.

Based on the method names, i thought the way to do it was :

short dateFormat = workbook.createDataFormat().getFormat("dd/MM/yyyy HH:mm");
...
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.getCellStyle().setDataFormat(dateFormat);

but, funny thing actually, it applies this style to ALL cells.

So, keeping in 开发者_C百科mind that i can't switch API (no upgrade, no csv, no jexcel), is there a way to achieve what i want ?

Thanks


Your problem is that you are changing the default cellStyle!
cell.getCellStyle() gives you the style that is currently set on that cell which usually is the default style if you haven't changed it yet.
In order to make this work as you expect you have to create a new CellStyle object from your dateFormat and set that to the cell like this:

dateStyle = workbook.createCellStyle();
...
dateStyle.setDataFormat(dateFormat);
cell.setCellStyle(dateStyle);

Also make sure that you create that style object only once and reuse it for all cells that you want to have that style.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号