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

5
我正在使用Apache POI读取一个现有的模板Excel文件,并希望将一些标题行中的现有样式复制并应用于新单元格。
看起来现有的格式没有被应用(例如日期、货币、百分比等)。
代码非常基本:
//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

所以这让我觉得我没有正确阅读格式。有什么想法可以实现这个吗?
1个回答

3

好的,我弄清楚了,那是我的错误。我从行中的第一个单元格读取样式并将其应用于所有单元格,而不是从每个单元格中读取。

这样就解决了问题。

Cell existingCell = existingRow.getCell(i);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接