list = new ArrayList();
try {
Workbook wb = WorkbookFactory.create(file.getInputStream());//适配针对excel 2003 和 excel 2007
// 获取Sheet(工作薄)
Sheet sheet = wb.getSheetAt(sheetAt);
// 开始行数
int firstRow = sheet.getFirstRowNum();
if(startRow != null){
firstRow = startRow;
}
// 结束行数
int lastRow = sheet.getLastRowNum()+1;
if(endRow != null){
lastRow = endRow;
}
// 判断该Sheet(工作薄)是否为空
boolean isEmpty = false;
if (firstRow == lastRow) {
isEmpty = true;
}
if (!isEmpty) {
for (int j = firstRow; j < lastRow; j++) {
// 获取一行
// XSSFRow row = sheet.getRow(j);
Row row=sheet.getRow(j);
if(row == null) {
throw new Exception("第" + (j + 1) + "行为空");
}
// 开始列数
int firstCell = row.getFirstCellNum();
if(startCell != null){
firstCell = startCell;
}
// 结束列数
int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();
if(endCell != null){
coloumNum = endCell;
}
int lastCell = row.getLastCellNum();
// 判断该行是否为空
String[] value = new String[coloumNum];
if (firstCell != lastCell) {
for (int k = firstCell; k < coloumNum; k++) {
// 获取一个单元格
Cell cell = row.getCell(k);
if(cell==null){
value[k] = "";
continue;
}
cell.setCellType(Cell.CELL_TYPE_STRING);
value[k] = cell.getStringCellValue();
}
}
// 每一行循环完对应的就是一个用户故事的所有属性全部拿到
list.add(value);
}
}
} catch (IOException e) {
try {
throw new Exception("非法模板{表头和模板表头不一致}") ;
} catch (Exception e1) {
//e1.printStackTrace();
log.error("非法模板{表头和模板表头不一致");
}
}catch (Exception e){
try {
throw new Exception("模板不符合要求,请下载模板");
} catch (Exception e1) {
//e1.printStackTrace();
log.error("模板不符合要求,请下载模板");
}
}
return list;
}
private static boolean isValidTitle(Row row) {
// 开始列数
int firstCell = row.getFirstCellNum();
int lastCell = row.getLastCellNum();
// 判断该行是否为空
if (firstCell != lastCell) {
for (int i = firstCell; i < lastCell; i++) {
// 获取一个单元格
Cell cell = row.getCell(i);
if(cell == null){
return false;
}
Object str = null;
// 获取单元格,值的类型
int cellType = cell.getCellType();
if (cellType == 1) {
str = cell.getStringCellValue();
}
if(!StringUtils.equalsIgnoreCase(TITLES[i], str.toString().trim())) {
return false;
}
}
return true;
} else {
return false;
}
}
}