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<java.lang.String,org.apache.poi.ss.usermodel.PictureData>
     * @Author: fan
     * @Date: 2023/5/22 11:05
     */
    public static Map<String, PictureData> 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<String, PictureData> pictures = getPictures(sheet);
            return pictures;
        } else if (fileName.endsWith("xlsx")) {
            //2007
            workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map<String, PictureData> pictures = getPictures(sheet);
            return pictures;
        }
        return new HashMap();
    }

    /**
     * @Description:获取excel表中的图片
     * @throws IOException
     * @throws EncryptedDocumentException
     * @param multipartFile 文件输入流
     * @param sheetNum  Excel表中的sheet编号
     * @return: java.util.Map<java.lang.String,org.apache.poi.ss.usermodel.PictureData>
     * @Author: fan
     * @Date: 2023/5/22 11:05
     */
    public static Map<String, PictureData> 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<String, PictureData> pictures = getPictures(sheet);
            return pictures;
        }
        return new HashMap();
    }

    /**
     * 获取图片和位置 (xls版)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map<String, PictureData> getPictures (HSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<HSSFShape> 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<String, PictureData> getPictures (XSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> 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<Map<String,Object>> getPictureList(MultipartFile multipartFile){
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            //获取图片数据
            Map<String, PictureData> 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<String, Object> 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<Map<String,Object>> getPictureList(String filePath){
        List<Map<String,Object>> list = new ArrayList<>();
        try {
            File file = new File(filePath);
            //获取图片数据
            Map<String, PictureData> 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<String, Object> 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<String, PictureData> map1 = getPictureFromExcel(file, 1);
        FileInputStream fileInputStream = new FileInputStream(filePath);
        MultipartFile multipartFile = new MockMultipartFile("test", fileInputStream);
        //String originalFilename = multipartFile.getOriginalFilename();
        //System.out.println("文件名-->" + originalFilename);
        List<Map<String, Object>> 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<String, Object> 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);
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值