赞
踩
以xlsx2007的excel为例
//获取整个文档 XSSFWorkbook wb; // 页 XSSFSheet sheet;//表 // 行 XSSFRow row;//行 // 打开文件 try { wb = new XSSFWorkbook(contactFile.get(i).getInputStream()); } catch (Exception e) { e.printStackTrace(); wb = new XSSFWorkbook(); } //获取第1页 sheet = wb.getSheetAt(0); // 得到总行数 int rowNum2 = sheet.getLastRowNum(); String uploadpath = "D://";//需要将图片保存的地址 //获取excel中的图片 Map<String, XSSFPictureData> pictureDataMap = getPictures(sheet); String savePath = ""; for (int k = 1; k <= rowNum2; k++) { String mapKey = k + "-" + 12;//指定行和列 if(pictureDataMap.get(mapKey)!=null){ XSSFPictureData xssfPictureData = pictureDataMap.get(mapKey); byte[] data = xssfPictureData.getData(); long time = System.currentTimeMillis(); //得到保存的file File file = bytesToFile(data, uploadpath, String.valueOf(time) + k + ".jpg"); } } //解析获取excel中的图片 public static Map<String, XSSFPictureData> getPictures( XSSFSheet xssfSheet){ Map<String,XSSFPictureData> sheetIndexPicMap=new HashMap<>(); for (POIXMLDocumentPart dr : xssfSheet.getRelations()) { if (dr instanceof XSSFDrawing) { XSSFDrawing drawing = (XSSFDrawing) dr; List<XSSFShape> shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { XSSFPicture pic = (XSSFPicture) shape; XSSFClientAnchor xssfClientAnchor=(XSSFClientAnchor) pic.getAnchor(); XSSFPictureData pdata = pic.getPictureData(); // 行号-列号 String key = xssfClientAnchor.getRow1() + "-" + xssfClientAnchor.getCol1(); sheetIndexPicMap.put(key, pdata); } } } return sheetIndexPicMap; } /** * 文件byte[]类型转File * * @param bytes bytes * @param outPath 输出目录 * @param fileName 文件名 * @return */ public static File bytesToFile(byte[] bytes, String outPath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(outPath); if (!dir.exists() && dir.isDirectory()) { //判断文件目录是否存在 dir.mkdirs(); } file = new File(outPath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。