使用poi读取excel数据

时间:2025-04-01 10:18:39
public class ReadExcelData { private String filePath;//excel的绝对路径 private String sheetName;//excel的sheet名称 public ReadExcelData(String filePath, String sheetName) { this.filePath = filePath; this.sheetName = sheetName; } public List<?> returnExcelData(Object object) throws IOException, IllegalAccessException, ParseException { FileInputStream fileInputStream = new FileInputStream(this.filePath);//开启文件读取流 XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);//读取文件 //获取sheet XSSFSheet sheet = sheets.getSheet(this.sheetName); // ();//获取sheet的数量,如果有多个sheet,可以使用for List<Object> list = new ArrayList<>(); //获取行数 int rows = sheet.getPhysicalNumberOfRows(); for(int i=1;i<rows;i++){ HashMap<String,String> readData = new HashMap<>(); //获取列数 XSSFRow row = sheet.getRow(i); int columns = row.getPhysicalNumberOfCells(); Field[] fields = object.getClass().getDeclaredFields(); for(int j=0;j<columns;j++){ //拿到单元格数据 XSSFCell cell = row.getCell(j); //判断单元格中数据的类型,根据类型进行赋值 switch (cell.getCellType()){ case XSSFCell.CELL_TYPE_STRING ://String readData.put(fields[j].getName(),cell.getStringCellValue());//属性赋值 break; case XSSFCell.CELL_TYPE_BOOLEAN ://bealean readData.put(fields[j].getName(),Boolean.valueOf(cell.getBooleanCellValue()).toString());//属性赋值 break; case XSSFCell.CELL_TYPE_NUMERIC ://number //默认日期读取出来是数字,判断是否是日期格式的数字 if(DateUtil.isCellDateFormatted(cell)){ //读取的数字是日期,转换一下格式 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = cell.getDateCellValue(); readData.put(fields[j].getName(),dateFormat.format(date));//属性赋值 }else {//不是日期直接赋值 readData.put(fields[j].getName(),Double.valueOf(cell.getNumericCellValue()).toString());//属性赋值 } break; case XSSFCell.CELL_TYPE_BLANK : readData.put(fields[j].getName(),"");//属性赋值 break; default: System.out.println("未知类型------>"+cell); } } // ("NO."+i+"数据读取成功"); list.add(readData); } return list; } }