POI框架开发经验贴
来源:互联网 发布:数据库管理系统培训 编辑:程序博客网 时间:2024/06/05 07:19
POI框架使用了一段时间,总结下自己的使用经验。
1. 07版excel行的上限
Short.max_value,超过这个值会报错
2. 下拉列表能包含的最多字符个数
下拉列表能包含的最多字符个数256个,超了就不显示。如果下拉列表的数据超过了256个字符,只能用函数的方式引用另一列作为数据源
3. 不同workbook类实例间不能复制样式
This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?java.lang.IllegalArgumentException: This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook? at org.apache.poi.xssf.usermodel.XSSFCellStyle.verifyBelongsToStylesSource(XSSFCellStyle.java:120) at org.apache.poi.xssf.usermodel.XSSFCell.setCellStyle(XSSFCell.java:651) at org.apache.poi.xssf.usermodel.XSSFCell.copyCellFrom(XSSFCell.java:184) at org.apache.poi.xssf.usermodel.XSSFRow.copyRowFrom(XSSFRow.java:640)
4. 向cell设置非string类型的值
向cell设置非string类型的值时,同时要设置cell的类型。否则打开excel的时候excel会有错误提示,“数字类型以字符串形式存储”,poi这一点做的不完善。
destRowCell.setCellValue(sourceRowCell.getNumericCellValue()); destRowCell.setCellType(CellType.NUMERIC);
5. org.apache.poi.xssf.usermodel.XSSFSheet#autoSizeColumn(int, boolean), 这个方法一定要放在excel处理的最后使用,一开始就用或者中途用达不到效果
6. 强制用户从下拉列表中取值
加了这个校验,一旦用户手动输入,excel会立即报错
XSSFDataValidation dataValidation = (XSSFDataValidation) helper.createValidation(constraint, regions); dataValidation.createErrorBox("输入错误", "请从下拉列表中取值"); dataValidation.setShowErrorBox(true);
7. 单元格背景色
XSSFCellStyle errorCellStyle = errorBook.createCellStyle();errorCellStyle.setFillForegroundColor(new XSSFColor(Color.RED));errorCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
setFillBackgroundColor,这个方式无效
8. 设置row高度
org.apache.poi.xssf.usermodel.XSSFSheet#setDefaultRowHeightInPoints不可靠,在mac上,压缩之后,填了数据的行,会恢复设置前的默认高度
9. 设置列宽
org.apache.poi.xssf.usermodel.XSSFSheet#autoSizeColumn(int),在单元格有中文的情况下,会出问题(mac上2016版不会有问题),正确的方式是取出字符串的字节数,再乘以256
xssfSheet.setColumnWidth(columnIndex, excelColumnModel.getLabel().getBytes().length * 256);
10. excel支持的最大行数和列数
在POI的这个类里有定义,包括03版一下的和07版以上的
org.apache.poi.ss.SpreadsheetVersion
11. sheet名字的最大长度
30个字符,超了就会被excel自动截断。
12. XssfWorkBook解析Ole2格式的elsx会报如下异常。部分2007版excel用户会报如下错误,可能是excel客户端的问题
org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)
03版一下的excel文件用HssfWorkBook打开,07版以上的excel文件则需要用XssfWorkBook类打开,如果串了,就会报错
13. 日期数据的判断与解析
日期数据是org.apache.poi.ss.usermodel.CellType#NUMERIC的一个特例,当一个单元格是Numeric类型的时候,再用下面的方法判断是否是日期类型
if (DateUtil.isCellDateFormatted(cell)) { Date dateCellValue = cell.getDateCellValue();}DateUtil全路径: org.apache.poi.ss.usermodel.DateUtil
阅读全文