POI读取Excel

来源:互联网 发布:三大男高音 知乎 编辑:程序博客网 时间:2024/05/17 07:21

POI读取Excel

传入文件地址,读取Excel文件

public static void readExcel(String file) throws Exception{        boolean isExcel2003 = file.toLowerCase().endsWith("xls")?true:false;        Workbook workbook = null;        if(isExcel2003){            workbook = new HSSFWorkbook(new FileInputStream(new File(file)));        }else{            workbook = new XSSFWorkbook(new FileInputStream(new File(file)));        }        Sheet sheet = workbook.getSheetAt(0);        Row row = null;        for (int i = 1; sheet.getRow(i)!=null; i++) {            row = sheet.getRow(i);            //日起类型的格式化            String pagetime = "";            if(row.getCell(2).getCellType() == Cell.CELL_TYPE_STRING){                  row.getCell(2).setCellType(Cell.CELL_TYPE_NUMERIC);              }            if(row.getCell(2).getCellType()==Cell.CELL_TYPE_NUMERIC){                 if (HSSFDateUtil.isCellDateFormatted(row.getCell(2))) { //Excel Date类型处理                      Date date = HSSFDateUtil.getJavaDate(row.getCell(2).getNumericCellValue());                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");                      pagetime = sdf.format(date);                }            }            String address = getCellValue(row.getCell(1));            String name = getCellValue(row.getCell(3));            String tel = getCellValue(row.getCell(4));        }    }

过滤获取的数据格式

public static String getCellValue(Cell cell){          String cellValue = "";          if(cell == null){              return cellValue;          }         int cellType = cell.getCellType();        if(cellType == Cell.CELL_TYPE_NUMERIC){              cell.setCellType(Cell.CELL_TYPE_STRING);          }          if(cellType==Cell.CELL_TYPE_NUMERIC){ //数字            cellValue = String.valueOf(cell.getNumericCellValue());         }else if(cellType==Cell.CELL_TYPE_STRING){ //字符串            cellValue = String.valueOf(cell.getStringCellValue());          }else if(cellType==Cell.CELL_TYPE_BOOLEAN){ //Boolean            cellValue = String.valueOf(cell.getBooleanCellValue());        }else if(cellType==Cell.CELL_TYPE_FORMULA){ //公式            cellValue = String.valueOf(cell.getCellFormula());        }else if(cellType==Cell.CELL_TYPE_BLANK){ //空值            cellValue = "";        }else(cellType==Cell.CELL_TYPE_ERROR){ //故障              cellValue = "未知类型";        }        return cellValue;      }

如果是导数据到服务器的话,我是先上传,最后处理完了再删除。

public static boolean delete(String path)    {        boolean flag=false;        File f = new File(path);        if(f.exists()){            flag = f.delete();        }        return flag;    }
1 0
原创粉丝点击