2012-09-11 37 views
3

我使用Apache POI来读取现有的模板excel文件,并且想要复制某些标题行中的现有样式并将它们应用于新单元格。Apache POI保留现有的Excel格式样式

似乎现有的格式不适用(IE,日期,货币,百分比等)。

的代码非常简单:

//read existing style 
Row existingRow = sheet.getRow(headerRowIndex); 
Cell existingCell = existingRow.getCell(0); 
CellStyle currentStyle = existingCell.getCellStyle(); 


//apply date style here 
Date date = StringUtil.toDate(map.get(column.getHeaderName())); 
cell.setCellValue(date); 
//apply previous style  
cell.setCellStyle(currentStyle); 

它确实复制字体和背景颜色等,但它似乎像格式化丢失(所有单元的“常规”格式应用)。

此外,当我这样做:

currentStyle.getDataFormat(); // always 0 

所以这让我觉得,我不能正确读取的格式。任何想法如何实现这一目标?

回答

0

好吧,我明白了,这是我的错。我正在读取行中第一个单元格的样式,并将其应用于所有单元格,而不是从每个单元格中读取。

这修复它

Cell existingCell = existingRow.getCell(i);