问题
In my java class I am declaring cell like:
HSSFCell cell = null;
And I am using this cell in many places to create a cell and set values, styles. Like:
cell = row.createCell(1);
cell.setCellValue("1234.00");
setCellStyle(currency, cell, workbook);
cell = row.createCell(2);
setCellValue("2445.00");
Now, surprisingly, the first cell's data format is being applied to 2nd cell. Anyone has any idea? I expect the 2nd cell's style to be none. And the 1st cell's style should be with the data format applied by setCellStyle() method. But, actually I am getting both the cell values with data format applied by setCellStyle() method.
setCellStyle() method:
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)"));
}
}
回答1:
Now that you've updated your post to show your setCellStyle
method, I can see the problem. Every Cell
starts out with a default CellStyle
, and they all share the same default CellStyle
. When you call setCellStyle
for the first Cell
, you are changing that default CellStyle
that is shared for all cells. This means that any other cells you create, where you don't set the CellStyle
have your changes. Additionally, any other time you call your own setCellStyle
, it will change the default cell style again.
Instead, create a new CellStyle
that only that Cell
will have, using Workbook's createCellStyle method.
HSSFCellStyle cellStyle = workbook.createCellStyle();
If you intend to set multiple cells to the same cell style, then you should 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.
来源:https://stackoverflow.com/questions/33833180/creating-a-new-cell-copies-previous-cells-style-in-apache-poi