Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。java
下图就是一个Workbook工做簿,也就是一张excel工做表。数据库
下图是工做簿的部分组件。apache
上面的图片很清晰的说明了一个工做簿的组成,就和咱们平时用的excel文档同样,而在咱们用POI解析Excel文件时,每一个组件都有相应的类,最主要的几个以下(建立一个新的工做簿):xss
(1) 一个Excel表格,就是一个Workbook工做簿类的对象。 Workbook workbook = new HSSFWorkbook(); (2) 一个Sheet工做表,就是一个Sheet类的对象,经过workbook获取。 Sheet sheet = workbook. createSheet(“工做表名字”); (3) 一行,就是一个Row类的对象,经过sheet获取。 Row row = sheet. createRow(0); (4) 一个单元格,就是一个Cell类的对象,经过row获取。 Cell cell = row.createCell((short)0); (5)单元格格式,是一个CellStyle类的对象,经过workbook设置。 CellStyle style = workbook.createCellStyle(); (6)单元格内容格式,是一个DataFormat类的对象,经过workbook设置。 DataFormat format= workbook.createDataFormat();
一. 建立一个文件流ui
InputStream is = new FileInputStream(excelPath);
二. 经过文件流读取已有的 Workbook工做簿(一切操做excel的基础类)。this
(1)Workbook book1 = new HSSFWorkbook(is); //excel文件后缀是xls (2)Workbook book2 = new XSSFWorkbook(is); //excel文件后缀是xlsx
三. 读取解析Sheet工做表,有两个方法:spa
(1)Sheet sheet = workbook.getSheet("Sheet1"); //经过表名读取工做表Sheet1 (2)Sheet sheet = workbook.getSheetAt(0); //经过索引读取第一张工做表
四. 获得工做表Sheet之后再读取每一行,将每一行存入一个实体。excel
Row row = sheet.getRow(rowNum); //rowNum为行号 Cell attribute = row.getCell(index); //获取每一行的每个字段,index为列号
好比student是一个实体,那么就将获取的每一个字段依次存入这个实体的每一个属性中。但存入以前首先要把Cell类的值转换成实体的属性对应类型,下面我写一个方法能够将cell转换成string类型:code
private String getValue(Cell cell) { if (null == cell) return null; if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) return String.valueOf(cell.getBooleanCellValue()); else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { DecimalFormat format = new DecimalFormat("#.##"); format.format(cell.getNumericCellValue()); return format.format(cell.getNumericCellValue()); } else return cell.getStringCellValue(); }
最后,将读取的每个字段一一存入实体,将实体更新到数据库就行了。orm
例:Student student = new Student(); student.setName(getValue(row.getCell(1)) ); student.setPassword(getValue(row.getCell(2)) );
下面的代码将一个Excel文件解析成一个List对象,能够经过List对象更新数据库表。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.students.xl.dto.StudentDTO; //解析Excel public class ExcelImport { Logger log = Logger.getLogger(this.getClass().getName()); public List<StudentDTO> readExcel(String filePath){ List<StudentDTO> list = new ArrayList<StudentDTO>(); //返回的学生集合 InputStream is = null; Workbook workbook = null; if("".equals(filePath)){ return null; }else{ try { is = new FileInputStream(filePath); //建立文件流 if("xls".equals(getPostFix(filePath))){ workbook = new HSSFWorkbook(is); //xls对应的HSSFWorkbook工做簿对象 }else if("xlsx".equals(getPostFix(filePath))){ workbook = new XSSFWorkbook(is); //xlsx对应的XSSFWorkbook工做簿对象 }else{ return null; } } catch (FileNotFoundException e) { e.printStackTrace(); log.error("[ExcelImport][readExcel]:Exception" + GetCalendar.getSysdate() + e.getMessage()); } catch (IOException e) { e.printStackTrace(); log.error("[ExcelImport][readExcel]:Exception" + GetCalendar.getSysdate() + e.getMessage()); } //循环遍历工做簿里面的sheet表 for(int i = 0; i < workbook.getNumberOfSheets(); i++){ Sheet sheet = workbook.getSheetAt(i); //读取工做表 if (sheet == null) //為空判斷 continue; for(int j = 1; j <= sheet.getLastRowNum(); j++){ Row row = sheet.getRow(j); //读取每行 if(row != null){ StudentDTO student = new StudentDTO(); //设置学生实体各属性的值 student.setSno(getValue(row.getCell(1))); student.setStu_name(getValue(row.getCell(2))); student.setStu_pass("8888"); student.setSex(getValue(row.getCell(3))); student.setXueyuan(getValue(row.getCell(4))); student.setMajor(getValue(row.getCell(5))); student.setS_class(getValue(row.getCell(6))); student.setPhone(getValue(row.getCell(7))); list.add(student); } } } } return list; } //获取文件后缀 private String getPostFix(String path) { if(path == null || "".equals(path.trim())){ return ""; } if(path.contains(".") && path.lastIndexOf(".") != path.length() -1 ){ return path.substring(path.lastIndexOf(".") + 1, path.length()); } return ""; } //转换Cell类型的值 private String getValue(Cell cell) { if (null == cell) return null; if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) return String.valueOf(cell.getBooleanCellValue()); else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { DecimalFormat format = new DecimalFormat("#.##"); format.format(cell.getNumericCellValue()); return format.format(cell.getNumericCellValue()); } else return cell.getStringCellValue(); } }
补充:(使用workbook须要的jar包)