Programming/Java
POI - Excel 파일 내에 이미지 추출
파란크리스마스
2017. 7. 22. 18:38
728x90
출처 : Apache POI - the Java API for Microsoft Documents
java - Get an image and its position from excel file using Apache POI
POI로 엑셀 파일 열기
import java.io.File; import java.io.FileInputStream; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class TestPoiMain { public static void main(String[] args) throws Exception { // String fileName = "test1.xlsx"; // File xlsFile = new File(fileName); Workbook workbook = null; try { if (xlsFile.exists()) { FileInputStream inputStream = new FileInputStream(xlsFile); workbook = new XSSFWorkbook(inputStream); System.out.println(workbook); } } finally { if (workbook != null) workbook.close(); } } }
POI로 Excel 파일 내에 이미지 추출
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFPictureData; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class TestPoiMain { public static void main(String[] args) throws Exception { // String fileName = "test1.xlsx"; String tarDir = "c:\\test"; // File xlsFile = new File(fileName); Workbook workbook = null; try { if (xlsFile.exists()) { FileInputStream inputStream = new FileInputStream(xlsFile); workbook = new XSSFWorkbook(inputStream); XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0); XSSFDrawing drawing = sheet.createDrawingPatriarch(); // I know it is ugly, actually you get the actual instance here for (XSSFShape shape : drawing.getShapes()) { if (shape instanceof XSSFPicture) { XSSFPicture picture = (XSSFPicture) shape; if (picture.getPictureData()==null) { System.out.println("사진 Path 사용"); continue; } XSSFPictureData xssfPictureData = picture.getPictureData(); ClientAnchor anchor = picture.getPreferredSize(); int row1 = anchor.getRow1(); int row2 = anchor.getRow2(); int col1 = anchor.getCol1(); int col2 = anchor.getCol2(); System.out.println("Row1: " + row1 + " Row2: " + row2); System.out.println("Column1: " + col1 + " Column2: " + col2); // Saving the file String ext = xssfPictureData.suggestFileExtension(); byte[] data = xssfPictureData.getData(); FileOutputStream out = new FileOutputStream(String.format("%s\\%s_%d_%d.%s", tarDir, sheet.getSheetName(), row1, col1, ext)); out.write(data); out.close(); } } } } finally { if (workbook != null) workbook.close(); } } }