Bootstrap

Java POI导入数据带图片

demo

@PostMapping("myUploadExcelEntityTest")
    public String myUploadExcelEntityTest(@RequestParam("fileName")MultipartFile fileName) throws Exception {

        if (fileName.isEmpty()) {
            return "文件为空,请重新上传";
        }

        if (!fileName.getOriginalFilename().endsWith(".xls")&&!fileName.getOriginalFilename().endsWith(".xlsx")) {
            return "上传文件不是excel类型";
        }

        InputStream fis = new BufferedInputStream(fileName.getInputStream());

        //获得第一张excel表
        Workbook workbook = WorkbookFactory.create(fis);

        List<Student> studentList = readExcel(Student.class, workbook);

        //读取图片,返回路径
        List<String> pic = getPic(workbook);


        for (int i=0;i<studentList.size();i++){

            studentList.get(i).setPicpath(pic.get(i));
            System.out.println(studentList.get(i));

        }


        return "good";

    }

    public List<String> getPic(Workbook workbook) throws IOException {

        List<? extends PictureData> allPictures = workbook.getAllPictures();

        List<String> picPath = new ArrayList<>();

        for (PictureData pic:allPictures ) {

            //文件扩展名
            String ext = pic.suggestFileExtension();
            byte[] data = pic.getData();

            String path = "D:/tmpCanDel/"+new Date().getTime() + "." + ext;
            File file = new File(path);

            //图片保存路径
            FileOutputStream out = new FileOutputStream(file);

            picPath.add(path);
            //IOUtils.copy(file,FileOutputStream)
            out.write(data);
            out.close();

        }

        return picPath;

    }
    

    //对一张表,进行实体映射
    private static <T> List<T> readExcel(Class<T> classzz,Workbook workbook) throws Exception {

        Sheet sheet = workbook.getSheetAt(0);

        //获取最后一行
        int lastRowNum = sheet.getLastRowNum()+1;
        //获取最后一列
        int lastCellNum = sheet.getRow(0).getLastCellNum();
        //获取实体类字段
        Field[] fields = classzz.getDeclaredFields();

        Row row = null;

        List<String> headList = new ArrayList<>();

        //一行存为一个Obj,放在List中
        List<T> beans = new ArrayList<T>();

        //获取表头放在list中
         for (int j=0;j<lastCellNum;j++){
             row = sheet.getRow(0);
             Cell cell = row.getCell(j);
             //均格式化为字符串
             DataFormatter formatter = new DataFormatter();
             String value = formatter.formatCellValue(cell);
             headList.add(value);
          }


         for (int i=1;i<lastRowNum;i++){

             //通过class创建实体对象
             T instance = classzz.newInstance();
             for (int j=0;j<lastCellNum;j++){

                 row = sheet.getRow(i);
                 Cell cell = row.getCell(j);
                 DataFormatter formatter = new DataFormatter();
                 String value = formatter.formatCellValue(cell);

                 String headName = headList.get(j);

                 for (Field field : fields){

                     if (headName.equalsIgnoreCase(field.getName())){

                         String methodName = MethodUtils.setMethodName(field.getName());
                         Method method = classzz.getMethod(methodName,field.getType());
                         //注入值
                         method.invoke(instance,value);
                     }

                 }

             }

             beans.add(instance);

         }

         return beans;

    }

    //内部静态类
    static class MethodUtils {
        private static final String SET_PREFIX = "set";
        private static final String GET_PREFIX = "get";
        private static String capitalize(String name) {
            if (name == null || name.length() == 0) {
                return name;
            }
            //set+首字母大写 比如setSid
            return name.substring(0, 1).toUpperCase() + name.substring(1);
        }
        public static String setMethodName(String propertyName) {
            return SET_PREFIX + capitalize(propertyName);
        }
        public static String getMethodName(String propertyName) {
            return GET_PREFIX + capitalize(propertyName);
        }
    }

在这里插入图片描述

在这里插入图片描述

pom文件

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
;