java excel通用导入类_java excel 文件导入通用接口

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值