一、POI解释:Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
二、我们要用的是:HSSF - 提供读写Microsoft Excel格式档案的功能。
三、需要导入的包:
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook;</span>
读取Excle表格的函数(这里以读取实验室课表为例):
// 从Excle读取课表 public List<LabIfo> readLabIfos(String filePath) throws IOException { // 读取Excle表格 InputStream inputStream = new FileInputStream(filePath); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream); List<LabIfo> labIfos = new ArrayList<LabIfo>(); // 循环工作表 for (int sheetNum = 0; sheetNum < hssfWorkbook.getNumberOfSheets(); ++sheetNum) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(sheetNum); if (hssfSheet == null) continue; // 循环row(排),忽略第一排的表项,getLastRowNum()是得到最后一个不为空的row的序号 for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); ++rowNum) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) continue; LabIfo labIfo = new LabIfo(); // 循环cell(单元格) // 0-实验室名 1-上课班级 2-周 3-天 4-节 5-备注 for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); ++cellNum) { HSSFCell hssfCell = hssfRow.getCell(cellNum); switch (cellNum) { case 0: if (hssfCell.getNumericCellValue() == 0.0) continue; // System.out.println(String.valueOf((int) hssfCell.getNumericCellValue())); labIfo.setLabName(String.valueOf((int) hssfCell.getNumericCellValue())); break; case 1: if (hssfCell.getStringCellValue() == null) continue; // System.out.println(hssfCell.getStringCellValue()); labIfo.setUserName(hssfCell.getStringCellValue()); break; case 2: if (hssfCell.getNumericCellValue() == 0.0) continue; // System.out.println(String.valueOf((int) hssfCell.getNumericCellValue())); labIfo.setWeek((int) hssfCell.getNumericCellValue()); break; case 3: if (hssfCell.getNumericCellValue() == 0.0) continue; // System.out.println(String.valueOf((int) hssfCell.getNumericCellValue())); labIfo.setDay((int) hssfCell.getNumericCellValue()); break; case 4: if (hssfCell.getNumericCellValue() == 0.0) continue; // System.out.println(String.valueOf((int) hssfCell.getNumericCellValue())); labIfo.setLesson((int) hssfCell.getNumericCellValue()); break; case 5: if (hssfCell.getStringCellValue() == null) continue; // System.out.println(hssfCell.getStringCellValue()); labIfo.setApplyReason(hssfCell.getStringCellValue()); break; default: break; } } labIfos.add(labIfo); } } return labIfos; }
1.函数参数filePath是Excle文件的绝对路径
2.格式对应:
hssfCell.getNumericCellValue()
用于读取单元格内数字(double)类型的数据
hssfCell.getStringCellValue()用于读取单元格内字符串类型(String)的数据
读取的时候,数据类型不对应会报错
2.忽略无数据的单元格:
if (hssfCell.getNumericCellValue() == 0.0) continue; if (hssfCell.getStringCellValue() == null) continue;
PS:原本在单元格输入了数据,后来把数据删除了,而单元格仍然在,这时候用
hssfSheet.getLastRowNum();读取数据的时候,会把这一排单元格读取进去(getLastRowNum()是得到最后一个不为空的row的序号)