java--poi读取excel图片和内容(支持03,07版本)

我做的是导入学生信息包括每个学生对应的证件照图片,所以此处不仅需要获取excel中的图片,还需要获取图片的位置信息,比如--哪行哪列的图片对应的是哪个学生,具体代码如下:

  public static void getDataFromExcel(String filePath) throws IOException
	    {
	        //String filePath = "E:\\123.xlsx";
	        
	        //判断是否为excel类型文件
	        if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
	        {
	            System.out.println("文件不是excel类型");
	        }
	        
	        FileInputStream fis =null;
	        Workbook wookbook = null;
	        Sheet sheet =null;
	        try
	        {
	            //获取一个绝对地址的流
	              fis = new FileInputStream(filePath);
	        }
	        catch(Exception e)
	        {
	            e.printStackTrace();
	        }
	       
	        try 
	        {
	            //2003版本的excel,用.xls结尾
	            wookbook = new HSSFWorkbook(fis);//得到工作簿
	             
	        } 
	        catch (Exception ex) 
	        {
	            //ex.printStackTrace();
	            try
	            {
	                //2007版本的excel,用.xlsx结尾
	            	 fis = new FileInputStream(filePath);
	                wookbook = new XSSFWorkbook(fis);//得到工作簿
	            } catch (IOException e)
	            {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
	        }
	        

	        Map  maplist=null;
	              
	        sheet = wookbook.getSheetAt(0);  
	            // 判断用07还是03的方法获取图片  
	        if (filePath.endsWith(".xls")) {  
	            maplist = getPictures1((HSSFSheet) sheet);  
	        } else if(filePath.endsWith(".xlsx")){  
	            maplist = getPictures2((XSSFSheet) sheet);  
	        }  
	        try {
				printImg(maplist);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	        //得到一个工作表
	        
	       
	        
	        //获得表头
	        Row rowHead = sheet.getRow(0);
	        
	        //判断表头是否正确
	        System.out.println(rowHead.getPhysicalNumberOfCells());
	        if(rowHead.getPhysicalNumberOfCells() != 5)
	        {
	            System.out.println("表头的数量不对!");
	        }
	        
	        //获得数据的总行数
	        int totalRowNum = sheet.getLastRowNum();
	        
	        //要获得属性
	       int studentid=0;
	       String studentname="";
	       String grade="";
	       String classes="";
	       String pic="";
	       //获得所有数据
	        for(int i = 1 ; i <= totalRowNum ; i++)
	        {
	            //获得第i行对象
	            Row row = sheet.getRow(i);
	            
	            //获得获得第i行第0列的 String类型对象
	            Cell cell = row.getCell((short)0);
	            studentid = (int) cell.getNumericCellValue();
	            
	            //获得一个数字类型的数据
	            //studentname = (int) cell.getNumericCellValue();
	            cell = row.getCell((short)1);
	            studentname =cell.getStringCellValue().toString();
	            
	            cell = row.getCell((short)2);
	            grade =cell.getStringCellValue().toString();
	            
	            cell = row.getCell((short)3);
	            classes =cell.getStringCellValue().toString();
	            
	            cell = row.getCell((short)3);
	            classes =cell.getStringCellValue().toString();
	            
	            System.out.println("学号:"+studentid+",姓名:"+studentname+",年级:"+grade+",班级:"+classes+",证件照:"+pic);
	        }
	        for (Entry entry : maplist.entrySet()) {  
	        	
	        	System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
	        	
	        }  
	    }
	  /**
	   * 获取图片和位置 (xls)
	   * @param sheet
	   * @return
	   * @throws IOException
	   */
	  public static Map getPictures1 (HSSFSheet sheet) throws IOException {
		    Map map = new HashMap();
		    List list = sheet.getDrawingPatriarch().getChildren();
		    for (HSSFShape shape : list) {
		        if (shape instanceof HSSFPicture) {
		            HSSFPicture picture = (HSSFPicture) shape;
		            HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
		            PictureData pdata = picture.getPictureData();
		            String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
		            map.put(key, pdata);
		        }
		    }
		    return map;
		}
	   
	  /**
	   * 获取图片和位置 (xlsx)
	   * @param sheet
	   * @return
	   * @throws IOException
	   */
	  public static Map getPictures2 (XSSFSheet sheet) throws IOException {
	      Map map = new HashMap();
	      List list = sheet.getRelations();
	      for (POIXMLDocumentPart part : list) {
	          if (part instanceof XSSFDrawing) {
	              XSSFDrawing drawing = (XSSFDrawing) part;
	              List shapes = drawing.getShapes();
	              for (XSSFShape shape : shapes) {
	                  XSSFPicture picture = (XSSFPicture) shape;
	                  XSSFClientAnchor anchor = picture.getPreferredSize();
	                  CTMarker marker = anchor.getFrom();
	                  String key = marker.getRow() + "-" + marker.getCol();
	                  map.put(key, picture.getPictureData());
	              }
	          }
	      }
	      return map;
	  }
	  //图片写出
	  public static void printImg(Map sheetList) throws IOException {  
          
	        //for (Map map : sheetList) {  
	            Object key[] = sheetList.keySet().toArray();  
	            for (int i = 0; i < sheetList.size(); i++) {  
	                // 获取图片流  
	                PictureData pic = sheetList.get(key[i]);  
	                // 获取图片索引  
	                String picName = key[i].toString();  
	                // 获取图片格式  
	                String ext = pic.suggestFileExtension();  
	                  
	                byte[] data = pic.getData();  
	                 
                //图片保存路径 
	                FileOutputStream out = new FileOutputStream("D:\\img\\pic" + picName + "." + ext);  
	                out.write(data);  
	                out.close();  
	            }  
	       // }  
	          
	    }  

public static void main(String[] args) throws Exception {
		  getDataFromExcel("E:"+ File.separator +"学生信息表.xlsx");
		  
		 
	}

效果如下:

java--poi读取excel图片和内容(支持03,07版本)_第1张图片

你可能感兴趣的:(java)