用poi解析excel,支持office2003、2007(xls,xlsx)

需要的jar包

poi-3.9-20121203.jar

poi-ooxml-3.9-20121203.jar

poi-ooxml-schemas-3.9-20121203.jar

xmlbeans-2.3.0_poi.jar


 /**
     *  Description:用poi解析excel,支持office2007 xls,xlsx
     *  @author liuwei  DateTime 2013-8-26 上午10:58:16
     *  @param fileName
     *  @param sheetNumber
     *  @return
     */
    public List<String[]> readByPoi(String fileName,int sheetNumber) {
    	org.apache.poi.ss.usermodel.Workbook workbook = null;
		List<String[]> list = new ArrayList<String[]>();
		try {
			String fileType=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
		        if (fileType.equals("xls")) {  
		        	workbook = new HSSFWorkbook(new FileInputStream(fileName));  
		        }  
		        else if(fileType.equals("xlsx"))  
		        {  
		        	workbook = new XSSFWorkbook(new FileInputStream(fileName));  
		        }  
		        else  
		        {  
		            log.info("您的文档格式不正确!");  
		        }  
		        //创建sheet对象  
			org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(sheetNumber);
			 int firstRowIndex = sheet.getFirstRowNum();  
	            int lastRowIndex = sheet.getLastRowNum(); 
	            int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();//获得总列数
	            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){  
	                Row row = sheet.getRow(rIndex);  
	                if(row != null){  
	                    int firstCellIndex = row.getFirstCellNum();  
	                    int lastCellIndex = row.getLastCellNum();  
	                    String[] s=new String[coloumNum];
	                    for(int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex ++){  
	                        Cell cell = row.getCell(cIndex);  
	                        String value = "";  
	                        int type = cell.getCellType();
	                        
	                        if(cell != null){  
	                        	value = cell.toString();  
	                        	if (Cell.CELL_TYPE_NUMERIC == type) { 
//	                        		 value = String.valueOf(cell.getNumericCellValue()); 
	                        		  Double val = cell.getNumericCellValue();
	                                  if(val == val.longValue()){
	                                      value= "" + val.longValue();
	                                  } 
	                        	}
	                        	
	                            s[cIndex]=value;  
	                        }  
	                    }  
	                    list.add(s);  
	                }  
	            }  

		} catch (Exception e) {
//			Log.error(e.getMessage());
			e.printStackTrace();
			
		} 
		return list;
	}


你可能感兴趣的:(用poi解析excel,支持office2003、2007(xls,xlsx))