Java 读取Excl文件 (poi-3.13)
2016-01-25 17:28
357 查看
最近做项目遇到了读取Excel数据到数据库做数据的初始化。于是找一个。发现(poi-3.13)可以解决问题。可以解析两种格式(xlsx和xls)
以下是实现的步骤
1.下载poi3.13包,地址(http://poi.apache.org/download.html#POI-3.13)
2.学习APi。
接下来是还是demo来说明问题吧:
1.准备Excel文件:
2.项目的目录结构:
代码实战:
结果展示:
就这样了,有问题可以联系我QQ:1561281670
以下是实现的步骤
1.下载poi3.13包,地址(http://poi.apache.org/download.html#POI-3.13)
2.学习APi。
接下来是还是demo来说明问题吧:
1.准备Excel文件:
2.项目的目录结构:
代码实战:
/** * 读取Excel数据 * @param file */ public List<Student> readExcel(File file){ List<Student> list = new ArrayList<Student>(); try { InputStream inputStream = new FileInputStream(file); String fileName = file.getName(); Workbook wb = null; if(fileName.endsWith("xls")){ //解析xls格式 wb = new HSSFWorkbook(inputStream); }else if(fileName.endsWith("xlsx")){ //解析xlsx格式 wb = new XSSFWorkbook(inputStream); } //第一个工作表 Sheet sheet = wb.getSheetAt(0); //第一行的行号 int firstRowIndex = sheet.getFirstRowNum(); //最后一行的行号 int lastRowIndex = sheet.getLastRowNum(); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){ //获取每一行 Row row = sheet.getRow(rIndex); Student student = new Student(); if(row != null){ //获取第一例 int firstCellIndex = row.getFirstCellNum(); int lastCellIndex = row.getLastCellNum(); for(int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex ++){ switch (cIndex) { case 0: student.setNo1(row.getCell(0).toString()); break; case 1: student.setNo2(row.getCell(1).toString()); break; case 2: student.setNo3(row.getCell(2).toString()); break; case 3: student.setNo4(row.getCell(3).toString()); break; case 4: student.setNo5(row.getCell(4).toString()); break; case 5: student.setNo6(row.getCell(5).toString()); break; case 6: student.setNo7(row.getCell(6).toString()); break; default: break; } } } list.add(student); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; }
结果展示:
就这样了,有问题可以联系我QQ:1561281670
相关文章推荐
- Java中的Enum的使用与分析
- spring boot简易入门
- The Java™ Tutorials —— Generics:前言
- Struts2设置默认的action
- Spring起步--helloworld
- 关于 Java 数组的 12 个最佳方法
- 【Eclipse】--Eclipse简介和安装
- 摘抄java基础
- Bean在Spring容器中的生命周期
- java 获取前几天时间
- struts2标签学习笔记(一)
- 【spring-mvc】spring mvc中得/和/*的区别
- Java基础之----异常处理(1.7以上)
- Java基础第一节
- Struts2 访问web元素
- spring注解注入失败一个原因
- spring jdbc多条件查询(参数化传参,防止sql注入风险)
- spring 与jedis2.7 集合
- java实现cassandra的增删改查
- 破解MyEclipse2013注册码