poi 读取excle,含有图片

阅读更多

maven 依赖

 


			org.apache.poi
			poi
			4.0.0
		
		
			org.apache.poi
			poi-ooxml
			4.0.0
		

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;

public class MyTest2 {

	private static final String EXCEL_XLS = "xls";
	private static final String EXCEL_XLSX = "xlsx";
	
	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "name";
	private static final String KEY_EMAIL = "email";
	//private static final String KEY_ICON = "icon";


	/**
	 * 判断文件是否是excel
	 * 
	 * @throws Exception
	 */
	public static void checkExcelVaild(File file) throws Exception {
		if (!file.exists()) {
			throw new Exception("文件不存在");
		}
		if (!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))) {
			throw new Exception("文件不是Excel");
		}
	}

	public static void main(String[] args) {

		try {
			File excelFile = new File("E:/product2.xlsx");
			FileInputStream in = new FileInputStream(excelFile);
			checkExcelVaild(excelFile);
			// Workbook workbook = getWorkbok(in, excelFile);
			Workbook workbook = WorkbookFactory.create(in);

			int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
			if (sheetCount <= 0) {
				return;
			}

			/**
			 * 设置当前excel中sheet的下标:0开始
			 */
			// Sheet sheet = workbook.getSheetAt(0); // 遍历第一个Sheet

			// 获取总行数
			// System.out.println(sheet.getLastRowNum());

			List> userListMap = new ArrayList<>();
			
			
			List> picListMap = new ArrayList<>();
			for (int i = 0; i < sheetCount; i++) { // 循环sheet页

				Sheet sheet = workbook.getSheetAt(i);
				
				//图片详细信息  key excle中的索引,value 图片信息
				Map sheetPictrues07 = getSheetPictrues07(i, (XSSFSheet)sheet, (XSSFWorkbook)workbook);
				picListMap.add(sheetPictrues07);
				
				int count = 0;
				for (Row row : sheet) { //循环行
					Map map = new HashMap<>();
					try {
						// 跳过第一行的目录
						if (count < 1) {
							count++;
							continue;
						}

						// 如果当前行没有数据,跳出循环
						if (row.getCell(0).toString().equals("")) {
							return;
						}

						// 获取总列数(空格的不计算)
						int columnTotalNum = row.getPhysicalNumberOfCells();
						System.out.println("总列数:" + columnTotalNum);

						System.out.println("最大列数:" + row.getLastCellNum());

						
						int end = row.getLastCellNum();
						for (int j = 0; j < end; j++) { // 循环列
							
							Cell cell = row.getCell(j);
							if (cell == null) {
								System.out.print("null" + "\t");
								continue;
							}

							Object obj = getValue(cell);
							if(j == 0){
								String userId = obj.toString();
								map.put(KEY_ID, userId);
							}
							if(j == 1){
								String name = obj.toString();
								map.put(KEY_NAME, name);
							}
							if(j == 2){
								String email = obj.toString();
								map.put(KEY_EMAIL, email);
							}
							/*if(j == 3){
								String icon = obj.toString();
								map.put(KEY_ICON, icon);
							}*/
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					userListMap.add(map);
				}
			}
			System.out.println(userListMap.toString());
			System.out.println(picListMap.toString());
			
			handlerImage(picListMap);
			

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	

	/**
	 * 处理图片
	 * @param picListMap  excle中图片详细信心,
	 * @throws Exception
	 */
	private static void handlerImage(List> picListMap) throws Exception {
		for (Map map : picListMap) {  
            Object key[] = map.keySet().toArray();  
            for (int i = 0; i < map.size(); i++) {  
                // 获取图片流  
                PictureData pic = map.get(key[i]);  
                // 获取图片索引  
                String picName = key[i].toString();  
                // 获取图片格式  
                String ext = pic.suggestFileExtension();  
                  
                System.out.println("索引--》"+picName);
                System.out.println("图片格式--》"+ext);
                
                // 写入图片到磁盘
                byte[] data = pic.getData();  
                FileOutputStream out = new FileOutputStream("E:\\testpoi\\pic" + picName + "." + ext);  
                out.write(data);  
                out.close();  
            }  
        }
		
	}

	/** 
     * 获取Excel2007图片 
     * @param sheetNum 当前sheet编号 
     * @param sheet 当前sheet对象 
     * @param workbook 工作簿对象 
     * @return Map key:图片单元格索引(0_1_1)String,value:图片流PictureData 
     */  
    public static Map getSheetPictrues07(int sheetNum,  
            XSSFSheet sheet, XSSFWorkbook workbook) {  
        Map sheetIndexPicMap = new HashMap();  
  
        for (POIXMLDocumentPart dr : sheet.getRelations()) {  
            if (dr instanceof XSSFDrawing) {  
                XSSFDrawing drawing = (XSSFDrawing) dr;  
                List shapes = drawing.getShapes();  
                for (XSSFShape shape : shapes) {  
                    XSSFPicture pic = (XSSFPicture) shape;  
                    XSSFClientAnchor anchor = pic.getPreferredSize();  
                    CTMarker ctMarker = anchor.getFrom();  
                    String picIndex = String.valueOf(sheetNum) + "_"  
                            + ctMarker.getRow() + "_" + ctMarker.getCol();  
                    sheetIndexPicMap.put(picIndex, pic.getPictureData());  
                }  
            }  
        }  
  
        return sheetIndexPicMap;  
    }  
      

	@SuppressWarnings("deprecation")
	private static Object getValue(Cell cell) {
		Object obj = null;
		switch (cell.getCellTypeEnum()) {
		case BOOLEAN:
			obj = cell.getBooleanCellValue();
			break;
		case ERROR:
			obj = cell.getErrorCellValue();
			break;
		case NUMERIC:
			obj = cell.getNumericCellValue();
			break;
		case STRING:
			obj = cell.getStringCellValue();
			break;
		default:
			break;
		}
		return obj;
	}

}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(poi 读取excle,含有图片)