我們在開發中可能會遇到將excel表中的數據存儲到數據庫中去,這就需要對excel進行解析
在操作過程中用到了poi-3.17.jar包
@Override
public List<ExcelModel> getTotals(String filePath) {
InputStream is;
HSSFWorkbook hssfWorkbook;
List<ExcelModel> list = null;
try {
is = new FileInputStream(filePath);
hssfWorkbook = new HSSFWorkbook(is);
ExcelModel excelModel = null;
list = new ArrayList<>();
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循環行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
excelModel = new ExcelModel();
HSSFCell id = hssfRow.getCell(0);
HSSFCell teacherName = hssfRow.getCell(1);
HSSFCell major = hssfRow.getCell(2);
HSSFCell title = hssfRow.getCell(3);
HSSFCell describe = hssfRow.getCell(4);
HSSFCell instruction = hssfRow.getCell(5);
HSSFCell exceptResult = hssfRow.getCell(6);
HSSFCell tel = hssfRow.getCell(7);
HSSFCell qq = hssfRow.getCell(8);
excelModel.setId(getValue(id));
excelModel.setTeacherName(getValue(teacherName));
excelModel.setMajor(getValue(major));
excelModel.setTitle(getValue(title));
excelModel.setDescribe(getValue(describe));
excelModel.setInstruction(getValue(instruction));
excelModel.setExceptResult(getValue(exceptResult));
excelModel.setTel(getValue(tel));
excelModel.setQq(getValue(qq));
list.add(excelModel);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 類型轉換
*/
@SuppressWarnings({ "deprecation", "static-access" })
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
// 返回布爾類型的值
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
// 返回數值類型的值
return String.valueOf(hssfCell.getNumericCellValue());
} else {
// 返回字符串類型的值
return String.valueOf(hssfCell.getStringCellValue());
}
}