Java poi 读取Excel内容
public class ImportExcelUtil {
private final static String excel2003L = ".xls";
private final static String excel2007U = ".xlsx";
private final static String excel2007X = ".xlsm";
public List<Dto> excelToList(InputStream in, String name) throws Exception {
Workbook work = getWorkbook(in, fileName);
List<Dto> dtoList = new ArrayList();
if (null == work) {
throw new Exception("Workbook is null");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
row = sheet.getRow(0);
String title[] = null;
if (row != null) {
title = new String[row.getLastCellNum()];
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
title[y] = (String) getCellValue(cell);
}
} else {
continue;
}
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
row = sheet.getRow(j);
Dto dto= new Dto();
for (int y = row.getFirstCellNum(); y < 13; y++) {
cell = row.getCell(y);
String key = title[y];
if (key.equals("姓名") && !getCellValue(cell).equals("")) {
dto.setName(getCellValue(cell));
}
}
}
dtoList.add(dto);
}
return dtoList;
}
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr);
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr);
}
else if(excel2007X.equals(fileType)){
wb = new XSSFWorkbook(inStr);
}
else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
}