最近业务上需要通过上传excel后,解析数据。规定用的poi版本是4.0 。特此记录一下 用户模式下 4.0和4.0以前版本的区别。
最主要的区别,就是poi4.0的row的索引是从0开始,而以前的版本是从1开始的。
//4.0+版本
for(int rowNum = 0;rowNum <= lastRowNum;rowNum++){
//具体方法
}
//以前的版本
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
XSSFRow row = sheet.getRow(j);
}
第二个区别,就是解析单元格的值有些许不同:
现在的解析方法如下:
/**
* 用户模式得到单元格的值
* @param workbook
* @param cell
* @return
*/
public static String getCellValue(Workbook workbook, Cell cell){
Assert.notNull(workbook, "when you parse excel, workbook is not allowed to be null");
String cellValue = "";
if (cell == null){
return cellValue;
}
switch (cell.getCellType()){
case NUMERIC:
cellValue = getDateValue(cell);
//判断日期类型
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = Constants.COMMON_DATE_FORMAT.format(cell.getDateCellValue());
break;
}
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
/**
* 格式化单元格
*/
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
cellValue = getCellValue(evaluator.evaluate(cell));
break;
case BLANK:
cellValue = "";
break;
case ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
case _NONE:
cellValue = "";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
/**
* 用户模式得到公式单元格的值
* @param formulaValue
* @return
*/
public static String getCellValue(CellValue formulaValue){
String cellValue = "";
if (formulaValue == null){
return cellValue;
}
switch (formulaValue.getCellType()){
case NUMERIC:
cellValue = String.valueOf(formulaValue.getNumberValue());
break;
case STRING:
cellValue = String.valueOf(formulaValue.getStringValue());
break;
case BOOLEAN:
cellValue = String.valueOf(formulaValue.getBooleanValue());
break;
case BLANK:
cellValue = "";
break;
case ERROR:
cellValue = String.valueOf(formulaValue.getErrorValue());
break;
case _NONE:
cellValue = "";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
然后是常量类
import java.text.SimpleDateFormat;
/**
* @author: youth_1231
* @Date: 2019/1/7 0007 16:14
* @Description:
*/
public interface Constants {
/**
* 年月日时分秒 默认格式
*/
SimpleDateFormat COMMON_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 07版excel后缀名
*/
String EXCEL_SUFFIX_07 = "xlsx";
/**
* 03版excel后缀名
*/
String EXCEL_SUFFIX_03 = "xls";
}
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
调用就不用说了吧?网上一大堆。
这就是解析poi4.0以后用户模式下解析excel的通用方法,网上有很多,但是网上方法经过调试整合后都会有不足之处,用了之后你会发现,比如日期、时间格式支持的并不好,数据量大的时候会内存溢出等等一系列问题,在这个系列的之后的文章中我会一一说明,并提供解决方法。最后我会将代码放到git上。
有不足之处请指正。联系方式详见我联系方式,或者发送邮箱 [email protected].