HSSFCell cell = row.createCell((short)i);
  cell.getCellStyle().setAlignment(HSSFCellStyle.ALIGN_RIGHT);
    ....
    你可能发现创建后的excel文件所有的列都变成右对齐了...
  
   翻了翻代码,还挺复杂,大意就是在创建的xls的时候会产生若干默认的ExtendedFormatRecord,这样在调用 row.createCell((short)i)创建普通的cell的时候,如果POI没有办法根据cell信息(i)找到对应的 ExtendedFormatRecord,则会返回固定的一个(at 0xF),这样在每次getCellStyle的时候返回的都是同一个style的reference. 所以对它的修改会影响整个xls文档.
  (上面说的不严谨,仅供参考)

 

解决方法:

   新建一个cellStyle,然后将原来的Style复制到新的style中,然后在这个新的style上进行操作。

 

//所以如果你需要修改某个cell的样式,如下
HSSFCell cell = row.createCell((short)i);  
HSSFCellStyle cStyle = wb.createCellStyle();  
//不直接使用getCellStyle(),用cloneStyleFrom就能实现保持原有样式
cStyle .cloneStyleFrom(cell.getCellStyle());               
cStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);  
cell.setCellStyle(cStyle); 

 

相关文章:

  • 2022-12-23
  • 2021-12-12
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-22
猜你喜欢
  • 2021-07-15
  • 2022-01-14
  • 2021-05-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
相关资源
相似解决方案