在我的java类中,我声明像以下单元格:
HSSFCell cell = null;
我在很多地方使用这个单元来创建一个单元格并设置值,样式.喜欢:
cell = row.createCell(1);
cell.setCellValue("1234.00");
setCellStyle(currency, cell, workbook);
cell = row.createCell(2);
setCellValue("2445.00");
现在,令人惊讶的是,第一个小区的数据格式正在应用于第二个小区.
任何人有任何想法?
我希望第二个细胞的风格是没有的.第一个单元格的样式应该是setCellStyle()方法应用的数据格式.
但是,实际上我通过setCellStyle()方法应用了数据格式的两个单元格值.
setCellStyle()方法:
public void setCellStyle(String currency, HSSFCell cell, HSSFWorkbook workbook){
HSSFCellStyle cellStyle = cell.getCellStyle();//I am using cell.getStyle() because the default cell style is not null for a HSSFCell
HSSFDataFormat dataFormat = workbook.createDataFormat();
if("GBP".equalsIgnoreCase(currency)){
cellStyle.setDataFormat(dataFormat.getFormat("[$£-809]#,##0_);[Red]([$£-809]#,##0)"));
}else (){
cellStyle.setDataFormat(dataFormat.getFormat("$#,##0_);[Red]($#,##0)"));
}
}
解决方法:
现在您已经更新了帖子以显示您的setCellStyle方法,我可以看到问题.每个Cell都以默认的CellStyle开始,它们都共享相同的默认CellStyle.当您为第一个Cell调用setCellStyle时,您将更改为所有单元共享的默认CellStyle.这意味着您创建的任何其他单元格(未设置CellStyle)都会进行更改.此外,在您调用自己的setCellStyle的任何其他时间,它将再次更改默认单元格样式.
HSSFCellStyle cellStyle = workbook.createCellStyle();
如果您打算将多个单元格设置为相同的单元格样式,那么您应该是reuse the CellStyle objects.
It is important to create a new cell style from the workbook otherwise you can end up modifying the built in style and effecting not only this cell but other cells.
标签:java,apache-poi
来源: https://codeday.me/bug/20190623/1271426.html