POI,Excel读写,兼容.xls、.xlsx

// POI 
        
    // 兼容.xls、.xlsx   参数:  路径 sheet 列 行  
    public static String readExcel(String path, String st, int i, int j) throws IOException {        
        File file = new File(path);
        String FileName = file.getName();
        String FileType = FileName.substring(FileName.lastIndexOf("."));        
        if (FileType.equals(".xlsx")) {            
            InputStream is = new FileInputStream(path);            
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
            XSSFSheet hssfSheet = xssfWorkbook.getSheet(st);
            XSSFRow hssfRow = hssfSheet.getRow(j);
            if (hssfRow != null) {
                String cell = hssfRow.getCell(i).toString();
                return cell;
            }
            return null;            
        } else if (FileType.equals(".xls")) {
            InputStream is = new FileInputStream(path);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
            HSSFSheet hssfSheet = hssfWorkbook.getSheet(st);
            HSSFRow hssfRow = hssfSheet.getRow(j);
            if (hssfRow != null) {
                String cell = hssfRow.getCell(i).toString();
                return cell;
            }
            return null;
        }
        return null;
    }
    
    // 兼容.xls、.xlsx 写 追加   
  //参数: 路径 sheet 列 行 插入字符串
public static void writeExcel(String path, String st, int i, int j, String str) throws FileNotFoundException, IOException { File file = new File(path); String FileName = file.getName(); String FileType = FileName.substring(FileName.lastIndexOf(".")); if (FileType.equals(".xlsx")) { InputStream is = new FileInputStream(path); XSSFWorkbook xwb = new XSSFWorkbook(is); XSSFSheet sheet = xwb.getSheet(st); if(sheet!=null) { XSSFRow row ; if(sheet.getRow(j)!=null) { row = sheet.getRow(j); }else { row = sheet.createRow(j); } XSSFCell cell = row.createCell(i); cell.setCellValue(str); xwb.write(new FileOutputStream(path)); } } else if (FileType.equals(".xls")) { InputStream is = new FileInputStream(path); HSSFWorkbook hwb = new HSSFWorkbook(is); HSSFSheet sheet = hwb.getSheet(st); if(sheet!=null) { HSSFRow row ; if(sheet.getRow(j)!=null) { row = sheet.getRow(j); }else { row = sheet.createRow(j); } HSSFCell cell = row.createCell(i); cell.setCellValue(str); hwb.write(new FileOutputStream(path)); } } }

 

posted @ 2018-08-01 11:37  AsapRun  阅读(379)  评论(0)    收藏  举报