java POI 解析excel 2003和2007 直接转为List 返回

时间:2022-01-20 07:06:57

1.POI 官网下载jar包,3.5以上

2.项目导入jar包

3.参数:String数组--对应的excel列名对应的KEY,File  excel文件,sheetNumber ---excel的sheet位置 0开始

public static List getExcelToList(String[]columnList,File path,int sheetNumber)throws Exception{

        List resultList =new ArrayList();
try { //解析excel 2003 xls/2007 xlsx
Workbook wookbook=WorkbookFactory.create(new FileInputStream(path));
//获取excel的sheet位置
Sheet sheet=wookbook.getSheetAt(sheetNumber);
//获取行数
//int rowNum=sheet.getPhysicalNumberOfRows();
int rownum=sheet.getLastRowNum();
//若行数为1 ,即只有行抬头,没有数据则返回
if(rownum<1){
return resultList;
}
//遍历行
for(int r=1;r<=rownum;r++){
Map rowMap=new HashMap();
//获取行
Row row=sheet.getRow(r);
if(row==null){
continue;
}
//遍历单元格cell
for(short c=0;c<row.getLastCellNum();c=(short) (c+1)){ Cell cell=row.getCell(c);
Object object=getCellInfo(cell);
rowMap.put(columnList[c],object);
}
resultList.add(rowMap);
}
return resultList;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} /**
*
* @Title: getCellInfo
* @Description:返回单元格对应的值
* @param cell
* @return
*/
public static Object getCellInfo(Cell cell){ Object resultObject=null;
if(cell!=null){
//单元格数据类型
int cellType=cell.getCellType();
switch (cellType) {
//值为空白
case Cell.CELL_TYPE_BLANK:
resultObject=null;
break;
//值为布尔
case Cell.CELL_TYPE_BOOLEAN:
resultObject=cell.getBooleanCellValue();
break;
//错误
case Cell.CELL_TYPE_ERROR:
resultObject=null;
break;
//值为String
case Cell.CELL_TYPE_STRING:
//resultObject=cell.getStringCellValue();
resultObject=cell.getRichStringCellValue().toString();
break;
//值为数值或者日期
case Cell.CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
double d=cell.getNumericCellValue();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date tempDate=DateUtil.getJavaDate(d);
resultObject=sdf.format(tempDate);
}else{
String ser = String.format("%20.2f", new Object[] { Double
.valueOf(cell.getNumericCellValue()) });
String ser2 = String.format("%20.0f", new Object[] { Double
.valueOf(cell.getNumericCellValue()) });
String fs = ser2.trim() + ".00";
if(fs.equals(ser.trim())){
resultObject=ser2.trim();
}else {
resultObject=ser.trim();
} }
break;
//公式
case Cell.CELL_TYPE_FORMULA:
resultObject=Double.valueOf(cell.getNumericCellValue());
break;
default:
System.out.println("枚举了所有类型"); }
}
return resultObject;
}

新手第一次发博,不对之处请指出~~~