POI解析Excel优化1
先来看看Excel导入的步骤吧
步骤1. excel文件校验
步骤2. excel文件上传
步骤3. 读取Excel
读取的时候可以这么认为,一行数据代表一个实体类,每一列代表实体类的一个成员变量,在读取的时候每次循环一行,就生成一个类,然后再给类的成员变量赋值。
这样的思路是没错,但是你会发现你的代码太长了,很多时候每次读取Excel里值得时候方法都是重复的,效率可想而知。
优化一: 对读取Excel里字段的方法进行封装
优化二: 一次性读取Excel里的内容,放在容器里面
优化代码如下:
public class ExcelValue {
public static List<List> getExcelValue(File file, String fileFileName) throws Exception{
List<List> valueList = new ArrayList();
List<String> stringList = new ArrayList();
String msg = "";
List strList = null ;
System.out.println(fileFileName);
FileInputStream is;
HSSFWorkbook wb;
try {
is = new FileInputStream(file);
wb = new HSSFWorkbook(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
msg = "无法读取文件。";
stringList.add(msg);
return valueList;
} catch (IOException e) {
e.printStackTrace();
msg = "读取文件错误。";
stringList.add(msg);
return valueList;
}
valueList.add(stringList);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;//行
HSSFCell cell = null;//单元格
//获取行数 从第0行开始
int rowNum = sheet.getLastRowNum();
for(int i = 1;i<=rowNum;i++){//从第二行开始
row = sheet.getRow(i);
//获取列数
int colNum = row.getPhysicalNumberOfCells();
strList= new ArrayList<String>();
for(int j=0 ;j<colNum;j++){
cell = row.getCell(j);
if(cell == null || StringUtils.isBlank(cell.toString())){
String str = "";
strList.add(str);
}else{
String str = getStringCellValue(cell);
strList.add(str);
}
}
valueList.add(strList);
}
return valueList;
}
/**
* 获取单元格数据内容为字符串类型的数据
* @param cell Excel单元格
* @return String 单元格数据内容
*/
public static String getStringCellValue(HSSFCell cell) {
String strCell = "";
if(cell==null){
return null;
}
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) { // 判断值为日期
strCell = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toLocaleString();
String[] dates = strCell.split(" ")[0].split("-");
String a = dates[0];
String a1 =dates[1];
String a2 = dates[2];
if(a1.length()==1){
a1="0"+a1;
}
if(a2.length()==1){
a2="0"+a2;
}
strCell = a+"-"+a1+"-"+a2;
}else{ // 纯数字
strCell = String.valueOf(cell.getNumericCellValue());
String[] s= strCell.split("\\.");
strCell = s[0];
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
if (strCell.equals("") || strCell == null) {
return "";
}
return strCell;
}
}