java读取excel文件的内容(包括图片)

直接上代码

package com.fan.li.utils;


import cn.hutool.core.codec.Base64Encoder;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName PicturesVo
 * @Description TODO
 * @Author fan
 * @Date 2023/5/22 9:33
 * @Version 1.0
 */
public class ReadXlsxPicturesUtil {

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }


    /**
     * @Description:获取excel表中的图片
     * @throws IOException
     * @throws EncryptedDocumentException
     * @param file 文件输入流
     * @param sheetNum  Excel表中的sheet编号
     * @return: java.util.Map
     * @Author: fan
     * @Date: 2023/5/22 11:05
     */
    public static Map getPictureFromExcel(File file, int sheetNum) throws EncryptedDocumentException, IOException {
        //获取图片PictureData集合
        String fileName = file.getName();
        Workbook workbook = null;
        if (StringUtil.isEmpty(fileName)) {
            return null;
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        if (fileName.endsWith("xls")) {
            //2003
            workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map pictures = getPictures(sheet);
            return pictures;
        } else if (fileName.endsWith("xlsx")) {
            //2007
            workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map pictures = getPictures(sheet);
            return pictures;
        }
        return new HashMap();
    }

    /**
     * @Description:获取excel表中的图片
     * @throws IOException
     * @throws EncryptedDocumentException
     * @param multipartFile 文件输入流
     * @param sheetNum  Excel表中的sheet编号
     * @return: java.util.Map
     * @Author: fan
     * @Date: 2023/5/22 11:05
     */
    public static Map getPictureFromExcel(MultipartFile multipartFile, int sheetNum) throws EncryptedDocumentException, IOException {
        //获取图片PictureData集合
        Workbook workbook = null;
        if (multipartFile != null) {
            workbook = new XSSFWorkbook(multipartFile.getInputStream());
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map pictures = getPictures(sheet);
            return pictures;
        }
        return new HashMap();
    }

    /**
     * 获取图片和位置 (xls版)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map getPictures (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 = picture.getClientAnchor();
                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 getPictures (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());*/
                    XSSFPicture picture = (XSSFPicture) shape;
                    //解决图片空指针报错问题 fan  2023-05-30
                    XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
//					XSSFClientAnchor anchor = pic.getPreferredSize();
                    CTMarker ctMarker = anchor.getFrom();
                    //解决用户头像格式错误   fan  2023-05-30
                    String picIndex = ctMarker.getRow() + "-" + anchor.getCol1();
                    map.put(picIndex, picture.getPictureData());
                }
            }
        }
        return map;
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    public static String doZero(String value) {
        String val = value;
        if (value.indexOf(".") != -1) {
            val = value.replaceAll("0+?$", "");
            val = val.replaceAll("[.]$", "");
        }
        return val;
    }



    /**
     * @desc:获取单元格内容
     * @param cell
     * @return
     *         异常时返回null
     */
    public static String getCellValueText(Cell cell) {
        try {
            String text = "";
            if (cell == null) {
                return text;
            } else {
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC://0
                        if (DateUtil.isCellDateFormatted(cell)) {// 判断是否为日期类型
                            //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                            return sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                        }
                        Double value = cell.getNumericCellValue();
                        BigDecimal bd = new BigDecimal(value + "");
                        text = bd.toPlainString();
                        text = doZero(text);
                        break;
                    case Cell.CELL_TYPE_STRING://1
                        text = cell.getStringCellValue().trim();
                    case Cell.CELL_TYPE_FORMULA://2
                        try {
                            text = String.valueOf(cell.getNumericCellValue());
                        } catch (IllegalStateException e) {
                            text = String.valueOf(cell.getRichStringCellValue());
                        }
                        break;
                }
                return text;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static List> getPictureList(MultipartFile multipartFile){
        List> list = new ArrayList<>();
        try {
            //获取图片数据
            Map map = getPictureFromExcel(multipartFile, 1);
            Workbook workbook = WorkbookFactory.create(multipartFile.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int lastRow = sheet.getLastRowNum();
            int lastCell = sheet.getRow(0).getLastCellNum();
            for (int i = 1; i <= lastRow; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map param = new HashMap<>();
                for (int j = 0; j < lastCell; j++) {
                    Cell cell = row.getCell(j);
                    String value = getCellValueText(cell);
                    if (value != null) {
                        value = value.trim();
                    }
                    if (j == 0) {
                        param.put("用户名", value);
                    }
                    if (j == 1) {
                        param.put("备注", value);
                    }
                    if (j == 2) {
                        param.put("类型", value);
                    }
                    if (j == 3) {
                        //根据图片行列位置获取图片
                        String key = "" + i + "-" + j;
                        PictureData picData = map.get(key);
                        if (picData != null) {
                            byte[] data = picData.getData();
                            if (data.length > 0) {
                                String base64 = Base64Encoder.encode(data);
                                param.put("人脸图", base64);
                                /*String extension = picData.suggestFileExtension();
                                FileOutputStream out = new FileOutputStream("C:\\my-word\\picture\\" + key + "_picture." + extension);
                                out.write(data);
                                out.close();*/
                            }
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(param)) {
                    list.add(param);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }


    public static List> getPictureList(String filePath){
        List> list = new ArrayList<>();
        try {
            File file = new File(filePath);
            //获取图片数据
            Map map = getPictureFromExcel(file, 1);
            FileInputStream fileInputStream = new FileInputStream(filePath);
            MultipartFile multipartFile = new MockMultipartFile("test", fileInputStream);
            Workbook workbook = WorkbookFactory.create(multipartFile.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int lastRow = sheet.getLastRowNum();
            int lastCell = sheet.getRow(0).getLastCellNum();
            System.out.println(lastRow + ", " + lastCell);
            for (int i = 1; i <= lastRow; i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map param = new HashMap<>();
                for (int j = 0; j < lastCell; j++) {
                    Cell cell = row.getCell(j);
                    String value = getCellValueText(cell);
                    if (value != null) {
                        value = value.trim();
                    }
                    if (j == 0) {
                        param.put("用户名", value);
                    }
                    if (j == 1) {
                        param.put("备注", value);
                    }
                    if (j == 2) {
                        param.put("类型", value);
                    }
                    if (j == 3) {
                        //根据图片行列位置获取图片
                        String key = "" + i + "-" + j;
                        PictureData picData = map.get(key);
                        if (picData != null) {
                            byte[] data = picData.getData();
                            if (data.length > 0) {
                                String base64 = Base64Encoder.encode(data);
                                param.put("人脸图", base64);
                                /*String extension = picData.suggestFileExtension();
                                FileOutputStream out = new FileOutputStream("C:\\my-word\\picture\\" + key + "_picture." + extension);
                                out.write(data);
                                out.close();*/
                            }
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(param)) {
                    list.add(param);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String [] args) throws Exception {
        String filePath = "C:\\my-word\\副本人脸批量上传辅助工具(1)(2).xlsm";
        //String filePath = "C:\\my-word\\工作簿1.xlsx";
        //File file = new File(filePath);
        //获取图片数据
        //Map map1 = getPictureFromExcel(file, 1);
        FileInputStream fileInputStream = new FileInputStream(filePath);
        MultipartFile multipartFile = new MockMultipartFile("test", fileInputStream);
        //String originalFilename = multipartFile.getOriginalFilename();
        //System.out.println("文件名-->" + originalFilename);
        List> pictureList =
                getPictureList(multipartFile).stream().filter(m ->
                        (!StringUtil.isEmpty(m.get("用户名").toString())
                                && !StringUtil.isEmpty(m.get("备注").toString())
                                && !StringUtil.isEmpty(m.get("类型").toString())
                                && !StringUtil.isEmpty(m.get("人脸图").toString())
                        )
                ).collect(Collectors.toList());;
                //getPictureList("C:\\my-word\\人脸.xlsx");
        System.out.println(pictureList.size());
        for(Map map : pictureList) {
            //log.info("{}", map);
            // 读取参数
            String userName = map.get("用户名") == null ? "" : map.get("用户名").toString();
            String remark = map.get("备注") == null ? "" : map.get("备注").toString();
            String type = map.get("类型") == null ? "" : map.get("类型").toString();
            String fileStr = map.get("人脸图") == null ? "" : map.get("人脸图").toString();
            System.out.println("fileStr-->" + fileStr);
        }
    }

}

你可能感兴趣的:(SpringBoot,java,excel,开发语言)