Android 讀取Excel文件

1.首先引入poi-3.9-20121203.jar、poi-ooxml-3.9-20121203.jar兩個jar包
2.

 /**
   *讀取本地excel文件
   **/
public static JSONArray  readExcel(File file)throws JSONException{  
    JSONArray array=new JSONArray();
    try {  
        InputStream inputStream = new FileInputStream(file);  
        String fileName = file.getName();  
        Workbook wb = null;  
        if(fileName.endsWith("xls")){  
            wb = new HSSFWorkbook(inputStream);//解析xls格式  
        }else if(fileName.endsWith("xlsx")){  
            wb = new XSSFWorkbook(inputStream);//解析xlsx格式  
        }  
        Sheet sheet = wb.getSheetAt(0);//第一個工作表  

        int firstRowIndex = sheet.getFirstRowNum(); 
        int lastRowIndex = sheet.getLastRowNum();  
        if(lastRowIndex>1){
            firstRowIndex=1;
        }
         //從第一行一直取到最後一行
        for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){ 
             //獲取excel中一行的數據
            Row row = sheet.getRow(rIndex); 
            if(row != null){  
                JSONObject obj=new JSONObject();
                obj.put("userName", getCellValue(0,row));
                obj.put("tel",  getCellValue(1,row));
                obj.put("position",getCellValue(2,row));
                obj.put("landline",getCellValue(3,row));
                obj.put("remark",getCellValue(4,row));
                array.put(obj);
            }  
        } 
        return array;
    } catch (FileNotFoundException e) {  
        return null;
    } catch (IOException e) {  
        return null;
    }  
} 

/**
 * 獲取cell值
 * @param key
 * @param pos
 * @param row
 * @return
 */
public static String getCellValue(int pos,Row row){
    Cell cell=row.getCell(pos);
    if(cell==null || StringUtil.isEmpty(cell.toString()))
        return "null";
    else 
        return cell.toString();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章