主要原因是多读数据,读到空表格或者类型问题(比如空字符串)
public boolean readExcel(String path) {
FileInputStream file;
try {
file = new FileInputStream(path);
try {
workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
for(int row=1;row<=sheet.getLastRowNum();row++){
HSSFRow sheetRow = sheet.getRow(row);
HSSFCell cell1 = sheetRow.getCell(0);
System.out.println("**************");
System.out.println("");
// System.out.println(cell1);
String collegecode = POIUtil.getInstance().getCellValue(cell1);
System.out.println(collegecode);
HSSFCell cell2 = sheetRow.getCell(1);
// System.out.println(cell2);
String college = POIUtil.getInstance().getCellValue(cell2);
System.out.println(college);
list.add(collegecode);
list.add(college);
map.put(row, list);
}
if(collgeService.saveExcelInfo(map)){
return true;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("【POI异常上传失败...】");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("【POI异常上传失败...】");
}
return false;
}
注:POI是从0开始的。
package com.synuatp.core.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
public class POIUtil
{
private POIUtil(){}
private static POIUtil poi= null;
public static POIUtil getInstance(){
if(poi==null){
synchronized(POIUtil.class){
if(poi==null){
poi = new POIUtil();
}
}
}
return poi;
}
public String getCellValue(HSSFCell cell){
String value = null;
//简单的查检列类型
// System.out.println("cell.getCellType():"+cell.getCellType());
switch(cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING://字符串
// System.out.println("HSSFCell.CELL_TYPE_STRING:"+HSSFCell.CELL_TYPE_STRING);
value = cell.getRichStringCellValue().toString();
break;
case HSSFCell.CELL_TYPE_NUMERIC://数字
// System.out.println("HSSFCell.CELL_TYPE_NUMERIC:"+HSSFCell.CELL_TYPE_NUMERIC);
long dd = (long)cell.getNumericCellValue();
value = dd+"";
break;
case HSSFCell.CELL_TYPE_BLANK:
// System.out.println("HSSFCell.CELL_TYPE_BLANK:"+HSSFCell.CELL_TYPE_BLANK);
value = "";
break;
case HSSFCell.CELL_TYPE_FORMULA:
// System.out.println("HSSFCell.CELL_TYPE_FORMULA:"+HSSFCell.CELL_TYPE_FORMULA);
value = String.valueOf(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值
// System.out.println("HSSFCell.CELL_TYPE_BOOLEAN:"+HSSFCell.CELL_TYPE_BOOLEAN);
value = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
// System.out.println("HSSFCell.CELL_TYPE_ERROR:"+HSSFCell.CELL_TYPE_ERROR);
value = String.valueOf(cell.getErrorCellValue());
break;
default:
// System.out.println("default");
break;
}
return value;
}
}