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包)