创建一个新单元格,在 Apache POI 中复制以前单元格的样式..?

Creating a new cell, copies previous cell's style in Apache POI..?

在我的 java class 中,我声明的单元格如下:

HSSFCell cell = null;

我在很多地方都使用这个单元格来创建单元格并设置值和样式。喜欢:

cell = row.createCell(1);               
cell.setCellValue("1234.00");
setCellStyle(currency, cell, workbook);

cell = row.createCell(2);               
setCellValue("2445.00");

现在,令人惊讶的是,第一个单元格的数据格式正在应用于第二个单元格。 有人知道吗? 我希望第二个单元格的样式为 none。第一个单元格的样式应使用 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)")); 
        }
}

现在您已经更新了 post 以显示您的 setCellStyle 方法,我可以看出问题所在。每个 Cell 都以默认值 CellStyle 开始,并且它们都共享相同的默认值 CellStyle。当您为第一个 Cell 调用 setCellStyle 时,您正在更改为所有单元格共享的默认值 CellStyle。这意味着您创建的任何其他未设置 CellStyle 的单元格都有您的更改。此外,任何其他时间您调用自己的 setCellStyle,它会再次更改默认单元格样式。

相反,使用 Workbook's createCellStyle method.

创建一个只有 Cell 才有的新 CellStyle
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.