您的位置:首页 > 编程语言

POI 导入excel代码总结

2016-01-13 16:45 239 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: