Apache POI保留现有的Excel格式样式

我正在使用Apache POI来读取现有的模板excel文件,并希望复制某些标题行中的现有样式,并将它们应用到新的单元格中。

看起来好像现有的格式没有被应用(IE,date,货币,百分比等)。

代码是非常基本的:

//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 

所以这让我觉得我没有正确阅读格式。 任何想法如何做到这一点?

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

这解决了它

 Cell existingCell = existingRow.getCell(i);