POI 导入excel代码总结
2016-01-13 16:45
239 查看
1.pom.xml 引入poi jar 包
2. 编写导入excel的代码
相应的User类就是手机号,密码,昵称三个属性,代码(略)
相应的excel的表,如图:
关于学习更多POI 可参考:http://poi.apache.org/spreadsheet/quick-guide.html
<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
相关文章推荐
- 用java的jni调用C语言的API,实现带图形界面的一元稀疏多项式计算器
- spring配置文件dubbo标签报错解决办法
- php 与 ajax 获取123的案例
- java学习--学生成绩管理系统
- Spring扫包时导致未加事务
- 真正解决RecyclerView在代码中创建无滚动条
- Eclipse创建mvn web工程
- spring cloud教程之使用spring boot创建一个应用
- struts2提交表单时Error setting expression 'user.username' with value……的错误
- 使用proguard混淆java web项目代码
- java与mysql数据类型对应表
- spring mvc web应用启动时就执行特定处理(线程启动)
- MyEclipse + Maven开发Web工程的详细配置过程
- Python操作Excel
- 用java解析在OpenStreetMap上下载的地图数据
- 7天学会spring cloud教程
- selenium+python自动化测试笔记(1)
- 关于烂代码的那些事(上)
- Java中系统属性Properties介绍 System.getProperty()参数大全
- java加密解密研究-MAC算法家族