问题描述
- 寻找个 用java poi 将xls转换成xlsx原有xls样式丢失问题的解决办法
-
最近在用java poi将原有财务部门的xls文件批量转换成xlsx格式,但是很不幸,xls原有的样式(比如:字体大小,字体颜色,背景)全部丢失了。
试着将原有xls里的style读出来设置给新的xlsx,但是遇到错误。
Code:
xlsxCell.setCellStyle(xlsCell.getCellStyle());Error:
java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFCellStyle cannot be cast to org.apache.poi.xssf.usermodel.XSSFCellStyle
at org.apache.poi.xssf.usermodel.XSSFCell.setCellStyle(XSSFCell.java:508)
解决方案
设置样式的时候 需要先new XSSFCellStyle 再复制copy属性 再添加 不能直接把HSSFCellStyle 转成XSSFCellStyle
解决方案二:
谢谢你的提示,试了下还是不行,难道需要针对每个style属性要一个一个的拿出来设进去吗?
Code
CellStyle hssfCellStyle = hssfCell.getCellStyle();
CellStyle xssfCellStyle = new XSSFCellStyle(new StylesTable());
xssfCellStyle.cloneStyleFrom(hssfCellStyle);
xssfCell.setCellStyle(xssfCellStyle);
Error
java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle
at org.apache.poi.xssf.usermodel.XSSFCellStyle.cloneStyleFrom(XSSFCellStyle.java:186)
解决方案三:
谢谢你的提示,试了下还是不行,难道需要针对每个style属性要一个一个的拿出来设进去吗?
Code
CellStyle hssfCellStyle = hssfCell.getCellStyle();
CellStyle xssfCellStyle = new XSSFCellStyle(new StylesTable());
xssfCellStyle.cloneStyleFrom(hssfCellStyle);
xssfCell.setCellStyle(xssfCellStyle);
Error
java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle
at org.apache.poi.xssf.usermodel.XSSFCellStyle.cloneStyleFrom(XSSFCellStyle.java:186)