1.pom.xml 引入poi jar 包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
2. 編寫導入excel的代碼
@SuppressWarnings("resource")
private List<User> readXls(String file) throws Exception{
List<User> list = new ArrayList<User>();
//創建一個工作簿
Workbook workbook = null;
try{
//Excel 2003及以前
workbook = new HSSFWorkbook(new FileInputStream(file));
}catch (Exception e){
//Excel 2007及以上
workbook = new XSSFWorkbook(new FileInputStream(file));
}
User importUser = null;
//循環工作表sheet
for(int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++){
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
//循環執行ROW(從第二行開始導入)
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
importUser = new User();
// 循環列Cell
// 0 手機號, 1 密碼, 2 暱稱
Cell xphone = row.getCell(0);
if(xphone==null){
continue;
}
importUser.setMobile(getValue(xphone));
Cell xpwd = row.getCell(1);
if(xpwd==null){
continue;
}
importUser.setPassword(getValue(xpwd));
Cell xnickname = row.getCell(2);
if(xnickname==null){
continue;
}
importUser.setNickName(getValue(xnickname));
list.add(importUser);
}
}
return list;
}
@SuppressWarnings("static-access")
private String getValue(Cell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
// 返回布爾類型的值
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
// 返回普通數值類型的值,因爲獲取的手機號會是科學計數法
DecimalFormat df = new DecimalFormat("0");
return df.format(cell.getNumericCellValue());
} else {
// 返回字符串類型的值
return String.valueOf(cell.getStringCellValue());
}
}
相應的User類就是手機號,密碼,暱稱三個屬性,代碼(略)
相應的excel的表,如圖:
關於學習更多POI 可參考:http://poi.apache.org/spreadsheet/quick-guide.html