首页 > 其他分享 >批量导入图片--Excel与zip压缩包

批量导入图片--Excel与zip压缩包

时间:2022-11-17 11:58:12浏览次数:40  
标签:String zip -- List Excel File peopleDtoList new null

导入excel和图片其实很简单,就是导入包与调用几个简单的方法,主要对接业务操作比较繁琐。

在excel中填入图片的名称(不用带后缀)

 

 对应的zip包

导入依赖

     <!--  zip压缩和解压 -->
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.10.5</version>
        </dependency>
Controller层
    /**
     * @Description: 导入excel和图片zip包
     * @Param:
     * @return:
     * @Author: jianhan
     * @Date: 2022-11-14 13:45:02
     **/
    @ApiOperation(value = "导入excel和图片zip包", notes = "导入excel和图片zip包")
    @PostMapping("/import/picture")
    public Result importExcelPic(@RequestPart MultipartFile excel, @RequestPart MultipartFile picture) throws Exception {
        StringBuffer sb = peopleService.importPicture(excel, picture, identity);
        if (sb!= null&&sb.length()>0) {
            return Result.failed(sb.toString());
        }else{
            return Result.success();
        }
    }

service层

@Value("${image.excelShortPath}")
public String excelShortPath;

@Value("${image.excelNginxPath}")
public String excelNginxPath;

 @Override
    public StringBuffer importPicture(MultipartFile excel, MultipartFile picture) throws Exception {
        String excelName = UUID.randomUUID() + ".xlsx";
        String qrCodeZIPName = UUID.randomUUID() + ".zip";
        StringBuffer sb = new StringBuffer();
        FileUtils.byte2File(excel.getBytes(), excelShortPath + excelName);
        String s1 = FileUtils.byte2File(picture.getBytes(), excelShortPath + qrCodeZIPName);
        String prefix = qrCodeZIPName.substring(qrCodeZIPName.lastIndexOf("."));
        int num = prefix.length();//得到后缀名长度
        String s2 = s1.substring(0, s1.length() - num);//得到文件名。去掉了后缀
        List<PeopleDto> getOriginalPic = ZipUtil.getOriginalPic(excelShortPath + s1, excelShortPath + s2);
        ExcelUtil<PeopleDto> util = new ExcelUtil<PeopleDto>(PeopleDto.class);
        List<PeopleDto> peopleDtoList = util.importExcel(excel.getInputStream());
        List<String> errorList = new ArrayList<String>();
        List<String> existCode = new ArrayList<String>();
        if (peopleDtoList.get(0).getCode().equals("123456") || peopleDtoList.get(0).getName().equals("示例")) {
            peopleDtoList.remove(0);//这里是删除excel第一条示例
        }
        for (int i = 0; i < peopleDtoList.size(); i++) {
            List<PeopleModel> peopleModelList = baseMapper.selectList(new QueryWrapper<PeopleModel>().eq("code", peopleDtoList.get(i).getCode()));
            if (peopleModelList != null && peopleModelList.size() > 0) {
                existCode.add(peopleDtoList.get(i).getCode());
                peopleDtoList.remove(i);//这里是删除重复数据
                continue;
            }
            int isWarn = 0;
            for (int j = 0; j < getOriginalPic.size(); j++) {
                if (peopleDtoList.get(i).getPictureName() == null) {
                    sb.append("第" + i + "行导入图片名称为空");
                }
                String fileName = getOriginalPic.get(j).getPictureName();
                String fix = fileName.substring(fileName.lastIndexOf("."));
                int number = fix.length();//得到后缀名长度
                String fileOtherName = fileName.substring(0, fileName.length() - number);//得到文件名。去掉了后缀
                if (peopleDtoList.get(i).getPictureName().equals(fileOtherName)) {
                    isWarn = 1;
                    peopleDtoList.get(i).setFaceImage(getOriginalPic.get(j).getFaceImage());
                    peopleDtoList.get(i).setPicture(excelNginxPath + s2 + "/" + getOriginalPic.get(j).getPictureName());//这里是存进数据库的url
                }
            }
            if (isWarn == 0) {
                errorList.add(peopleDtoList.get(i).getCode());
            }
        }
        if (existCode != null && existCode.size() > 0) {
            sb.append("学号为 " + existCode + " 的学号已存在数据库。");
        }
        if (errorList != null && errorList.size() > 0) {
            sb.append("学号为 " + errorList + " 的图片不存在或没有人脸。");
        }
        List<String> errorString = batchAdd(peopleDtoList);
        if (errorString.size() == 0) {
            return sb;
        } else {
            sb.append("失败学号列表:" + errorString);
        }
        return sb;
    }
FileUtils.byte2File
采用若依框架自带的文件处理FileUtils.byte2File
ZipUtil.getOriginalPic
    public static List<PersonDto> getOriginalPic(String zipPath,String unzipPath) throws Exception
      {
          unZip(zipPath);
          List<PersonDto> personDtoList=readfile(unzipPath);
          return personDtoList;
      }
ZipUtil.unZip
 public static void unZip(String path) {
        int count = -1;
        String savepath = "";
        File file = null;
        InputStream is = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        savepath = path.substring(0, path.lastIndexOf(".")) + File.separator; //保存解压文件目录
        new File(savepath).mkdir(); //创建保存目录
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(path, "gbk"); //解决中文乱码问题
            Enumeration < ? > entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                byte buf[] = new byte[buffer];
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String filename = entry.getName();
                boolean ismkdir = false;
                if (filename.lastIndexOf("/") != -1) { //检查此文件是否带有文件夹
                    ismkdir = true;
                }
                filename = savepath + filename;
                if (entry.isDirectory()) { //如果是文件夹先创建
                    file = new File(filename);
                    file.mkdirs();
                    continue;
                }
                file = new File(filename);
                if (!file.exists()) { //如果是目录先创建
                    if (ismkdir) {
                        new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs(); //目录先创建
                    }
                }
                file.createNewFile(); //创建文件
                is = zipFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos, buffer);
                while ((count = is.read(buf)) > -1) {
                    bos.write(buf, 0, count);
                }
                bos.flush();
                bos.close();
                fos.close();
                is.close();
            }
            zipFile.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
ZipUtil.readfile
public static List<PeopleDto> readfile(String filepath) throws Exception {
        File file = new File(filepath);
        List<PeopleDto> personDtoList = new LinkedList<PeopleDto>();
        if (!file.isDirectory()) {
            return null;
        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                //windows 的读取方法
                File readfile = new File(filepath + "\\" + filelist[i]);
//                // linux 的读取方法
//                File readfile = new File(filepath + "/" + filelist[i]);
                if (!readfile.isDirectory()) {
                    String fileName = readfile.getName();
                    //System.out.println("fileOtherName:"+fileOtherName);
                    File file1Save = new File(readfile.getAbsolutePath());
                    byte[] byteBuffer = FileUtil.readBytes(file1Save);
                    PeopleDto peopleDto = new PeopleDto();
                    peopleDto.setFaceImage(byteBuffer);
                    peopleDto.setPictureName(fileName);
                    personDtoList.add(peopleDto);
                } else if (readfile.isDirectory()) {
                    return null;
                }
            }
        }
        return personDtoList;
    }
util.importExcel
这里采用ruoyi框架的通用的excel导入,也可以用其他Excel导入方式完成这部分
batchAdd
 private List<String> batchAdd(List<PeopleDto> peopleDtoList) {
        List<String> errorString = new LinkedList<String>();
        List<PeopleModel> peopleModels = new ArrayList<>();
        if (peopleDtoList.size() > 0 && peopleDtoList != null) {
            for (PeopleDto personDto : peopleDtoList) {
                PeopleModel peopleModel = new PeopleModel();
                BeanUtils.copyProperties(personDto, peopleModel);
              //这里可以判断数据库是否有重叠数据,和一些具体业务
                
                peopleModels.add(peopleModel);
            }
            if (this.saveBatch(peopleModels)) {
                for (PeopleModel peopleModel : peopleModels) {
                    //这里可以做一些外接设备的业务处理
                    //errorString.add(peopleModel.getCode());
                }
            } else {
                errorString.add("保存数据库失败");
            }
        }
        return errorString;
    }                

 

 

 

标签:String,zip,--,List,Excel,File,peopleDtoList,new,null
From: https://www.cnblogs.com/SjhCode/p/excelAndPic.html

相关文章

  • mysql获取当前月,当前年天数(包含上个月,上一年天数)
     1、获取当前月天数:selectday(last_day(NOW())); 2、获取上一月天数:SELECTday(LAST_DAY(date_sub(curdate(),interval1MONTH)));  3、获取当前年的总......
  • JwtUtils
    packagecom.java1234.utils;importcom.java1234.common.JwtConstant;importcom.java1234.entity.CheckResult;importio.jsonwebtoken.*;importorg.bouncycastle.......
  • openjdk11源码编译调试
    一源码二系统工具macOSBigSur11.5.2Xcode12.5.1openjdk11.0.11Make3.81autoconf(GNUAutoconf)2.71Appleclangversion12.0.5(clang-1205.0.22.11)c......
  • StringUtil
    packagecom.java1234.utils;importjava.util.ArrayList;importjava.util.List;importjava.util.Random;/***字符串工具类*@author**/publicclassS......
  • Xshell中文显示乱码
    查看远程服务器编码locale,查看语言环境设置utf-8即可......
  • rokcetmq消息处理流程解决阻塞线程
    rokcetmq消息处理流程                   上面的处理订单调用采用异步调用解决阻塞问题,解决方式如下结论: ......
  • python读取文件列表修改txt内容
        importosfilePath='img'path2=r'/config/FHY_gps.txt'path3=r'/config/FHY_gps_new.txt'name=os.listdir(filePath)name.sort(key=lambdax......
  • Linux 用户及用户组相关文件、命令详解
    Linux用户及用户组相关文件、命令详解1.用户、用户组概念及其文件结构详解​ Linux用户只有两个等级:root及非root。Linux中还有一部分用户,如:apache、mysql、nobody、f......
  • 正则表达式中的预搜索
    格式:1.正向预搜索,右侧是或者不是什么:"(?=xxxxx)","(?!xxxxx)";2.反向预搜索,左侧是或者不是什么:"(?<=xxxxx)","(?<!xxxxx)"注意:1.括号是必须的且不参与反向引......
  • 后续内容的说明
    前面的8章37节阐述了本书媒介视角语言观的基本内容。核心的内容都是原创的,很大可能也是突破性的。理解这一点不能只是选取自己有兴趣的章节阅读,这样的效果只是补充自己原有......