利用poi读取远程excel文件的简单方法

   

 public static List<List<Object>> read(String fileUrl) throws IOException {
        List<List<Object>> allRows = new ArrayList<List<Object>>();
        InputStream is = null;
        Workbook wb = null;
        try {
            URL url = new URL(encodedUri);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3 * 60 * 1000);
            is = conn.getInputStream();
            wb = WorkbookFactory.create(is);
            Sheet sheet = wb.getSheetAt(0);
            int maxRowNum = sheet.getLastRowNum();
            int minRowNum = sheet.getFirstRowNum();
 
            // 跳过头,从第二行开始读取
            for (int i = minRowNum + 1; i <= maxRowNum; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                List<Object> rowData = readLine(row);
                allRows.add(rowData);
            }
 
        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            if (is != null) {
                is.close();
            }
            if (wb != null && wb instanceof SXSSFWorkbook) {
                SXSSFWorkbook xssfwb = (SXSSFWorkbook) wb;
                xssfwb.dispose();
            }
        }
 
        return allRows;
 
    //读取每行数据
    private static List<Object> readLine(Row row) {
        short minColNum = row.getFirstCellNum();
        short maxColNum = row.getLastCellNum();
        List<Object> dataList = new ArrayList<Object>();
        for (short colIndex = minColNum; colIndex < maxColNum; colIndex++) {
            Cell cell = row.getCell(colIndex);
            if (cell == null) {
                continue;
            }
            int cellType = cell.getCellType();
            Object value = null;
            if (Cell.CELL_TYPE_NUMERIC == cellType) {
                value = cell.getNumericCellValue();
            } else if (Cell.CELL_TYPE_STRING == cellType) {
                value = cell.getStringCellValue();
            } else {
                value = cell.getStringCellValue();
            }
            dataList.add(value);
        }
 
        return dataList;
    }

 

你可能感兴趣的:(Excel)