JAVA抠取Excel中的图片
Posted 长风傲天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA抠取Excel中的图片相关的知识,希望对你有一定的参考价值。
EXCEL中扔了一堆的图片,老大让对应到数据库中的数据上。思路先把图片抠出存成单个图片。然后上传到服务器,取下路径更新到数据库中。
注释掉的部分为有多个Excel时使用。
package com.zhaopin; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import com.ctc.wstx.util.StringUtil; public class ExcelImpTest { /** * * @param args * @Date 2016-1-29 */ public static void main(String[] args) { int totalCountaaaaa = 0; File file = new File("E:\\webchatcode.xlsx"); File filewrite = new File("E:"+File.separator + "webchatcodesql.sql"); XSSFWorkbook sw; try { int totalCount = 0; if(file.exists()){ // File[] files = fileDir.listFiles(); // for(File file:files){ sw = new XSSFWorkbook(new FileInputStream(file)); System.out.println(sw.getNumberOfSheets()); totalCount += sw.getNumberOfSheets(); String fileName = file.getName(); for(int i = 0;i<sw.getNumberOfSheets();i++){ XSSFSheet sheet = sw.getSheetAt(i); XSSFRow row = sheet.getRow(0); XSSFRow row1 = sheet.getRow(1); // String cValue = ""; // int cellNumber = 0; // if(row!=null){ // int lastCellCell = row.getLastCellNum(); // for(int j=0;j<lastCellCell;j++){ // XSSFCell cell = row.getCell(j); // XSSFCell cell1 = row1.getCell(j); // String cell1Value = ""; // if(cell==null){ // continue; // } // cValue = cell.getStringCellValue()==null?"":cell.getStringCellValue().trim(); // if("项目".equals(cValue)){ // cValue = "场地"; // cellNumber = j; // break; // } // if(cell1!=null){ // cell1Value = cell1.getStringCellValue()==null?"":cell1.getStringCellValue().trim(); // if("基本信息".equals(cValue)&&"学校等级".equals(cell1Value)){ // cValue = "校区"; // cellNumber = j; // break; // } // } // // // } // // // } // // if(cValue!=null&&"场地".equals(cValue)){ // System.out.println("isVenue:==========="+fileName+"::"+sheet.getSheetName().trim()); // cValue = "场地"; // }else if(cValue!=null&&"校区".equals(cValue)){ // System.out.println("isCampus:==========="+fileName+"::"+sheet.getSheetName().trim()); // cValue = "校区"; // }else{ // System.out.println("unKnow:==========="+fileName+"::"+sheet.getSheetName().trim()); // cValue = "unKnow"; // } String pathName = "E:/weiChat/"+sheet.getSheetName().trim()+"/"; File fileFolder = new File(pathName); if(!fileFolder.exists()){ fileFolder.mkdirs(); } Map<String, String> valueMap = getPicNameMap(sheet); Map<Integer,PictureData> map = new HashMap<Integer, PictureData>(); XSSFCell cell = null; //遍历sheet中的图片 for(POIXMLDocumentPart dr:sheet.getRelations()){ if(dr instanceof XSSFDrawing){ XSSFDrawing drawing = (XSSFDrawing)dr; List<XSSFShape> shapes = drawing.getShapes(); //如果是图形,进行遍历 int k = 0; for(XSSFShape shape:shapes){ k++; //如果是图片,保存图片,并获取图片信息 if(shape instanceof XSSFPicture && shape!=null){ XSSFPicture picture = (XSSFPicture)shape; if(picture == null){ continue; } try{ XSSFClientAnchor anchor = picture.getPreferredSize(); PictureData pic = picture.getPictureData(); CTMarker ctMarker = anchor.getFrom(); int startRowIndex = ctMarker.getRow(); int startColIndex = ctMarker.getCol(); XSSFRow rowaa = sheet.getRow(startRowIndex); cell = rowaa.getCell(14); String valTemp = ""; if(cell != null){ valTemp = String.valueOf(cell.getNumericCellValue()); valTemp = valTemp.substring(0,valTemp.length() -2); } // if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING){ //// cell = rowaa.getCell(startColIndex-2); // }else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ // cell = rowaa.getCell(startColIndex); // }else{ // cell = rowaa.getCell(startColIndex); // System.out.println("=====startRowIndex====="+startRowIndex+"==========startColIndex================"+startColIndex+"==="+cell.getCellType()); // } // // switch (cell.getCellType()) { // case HSSFCell.CELL_TYPE_STRING: // valTemp = cell.getStringCellValue(); //// System.out.println("=====startRowIndex===="+startRowIndex+"======startColIndex========="+startColIndex+"====valTemp====="+valTemp); // break; // case HSSFCell.CELL_TYPE_NUMERIC: //// valTempa = cell.getNumericCellValue(); // System.out.println("=====%%%%%%%%==="+startRowIndex+"======startColIndex========="+startColIndex); // totalCountaaaaa++; // break; // } // String valTemp = cell.getStringCellValue(); // System.out.println("=====startRowIndex===="+startRowIndex+"======startColIndex========="+startColIndex+"====valTemp====="+valTemp); String value = getpicName(sheet,valueMap,startRowIndex,startColIndex,valTemp); FileOutputStream os = new FileOutputStream(new File(pathName+value.replaceAll("/", "")+"."+pic.suggestFileExtension())); os.write(pic.getData()); os.flush(); os.close(); // byte bytes[] = new byte[512]; // bytes = content.getBytes(); // int b = content.length(); // FileOutputStream fos = new FileOutputStream(file); // fos.write(bytes, 0, b); // fos.close(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filewrite,true), "utf-8")); // String valueddd = valTemp+"_" + System.currentTimeMillis(); bw.write("UPDATE T_WEBCHAT_QUOTATION t SET t.CODEPICTURE = @#@#@"+pathName+value.replaceAll("/", "")+"."+pic.suggestFileExtension()+"@@@ WHERE t.ID = ‘"+valTemp+"‘;"); bw.newLine(); bw.close(); // response.getWriter().write("{\"result\":\"success\"}"); }catch (Exception e) { // e.printStackTrace(); // System.out.println(fileName+":::"+sheet.getSheetName()); } } } } } } } // } System.out.println(totalCount); System.out.println("==================="+totalCountaaaaa); // XSSFWorkbook nsw = null; // for(int i=0;i<sheetCount;i++){ // if(i==sheetCount-1){ // // break; // } // if(i%50==0){ // // nsw = new XSSFWorkbook(new FileInputStream(new File("……需求/temp/venue"+i/50+".xlsx"))); // } // XSSFSheet osheet = sw.getSheetAt(i); // XSSFSheet sheet = nsw.createSheet(osheet.getSheetName()); // sheet = osheet; // // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static Map<String, String> getPicNameMap(XSSFSheet sheet){ Map<String, String> valueMap = new HashMap<String, String>(); int merNums = sheet.getNumMergedRegions(); for(int j = 0;j<merNums;j++){ CellRangeAddress cRangeAddress = sheet.getMergedRegion(j); int startRow = cRangeAddress.getFirstRow(); int startCol = cRangeAddress.getFirstColumn(); int endRow = cRangeAddress.getLastRow(); int endCol = cRangeAddress.getLastColumn(); XSSFCell cell = sheet.getRow(startRow).getCell(startCol); sheet.getRow(startRow).getCell(startCol).setCellType(XSSFCell.CELL_TYPE_STRING); cell.setCellType(Cell.CELL_TYPE_STRING); if(startCol > 2){ valueMap.put(startRow+"-"+startCol+"-"+endRow+"-"+endCol, cell.getStringCellValue()); } } return valueMap; } public static String getpicName(XSSFSheet sheet,Map<String, String> valueMap,int startRowIndex,int startColIndex,String valTemp){ Iterator<String> it = valueMap.keySet().iterator(); String value = ""; while (it.hasNext()) { String key = it.next(); String[] keys = key.split("-"); if((startColIndex+"").equals(keys[1])){ if(startRowIndex >= Integer.parseInt(keys[0]) && startRowIndex <= Integer.parseInt(keys[2])){ value = valueMap.get(key); } } } if(StringUtils.isNotBlank(valTemp)){ value = valTemp+"_" + System.currentTimeMillis(); }else{ value = StringUtils.isNotBlank(value) ? (sheet.getSheetName().trim()+"_"+ value.trim()):(sheet.getSheetName().trim()+"_"+startRowIndex+"-"+startColIndex); } return value.replaceAll("/", ""); } }
以上是关于JAVA抠取Excel中的图片的主要内容,如果未能解决你的问题,请参考以下文章
java poi往excel里面插图片,怎样让图片在指定单元格范围内居中