Java实现导入包含多张照片和一个excel文件的zip包功能。

功能描述:

只导入用户信息文件,文件为excel文件。或者导入用户信息,同时导入用户的照片,一个excel中有10个人,照片有10张,根据人名命名照片名字,并将照片的部分信息保存到用户相应的表中。

注意:解压zip包,解压的地址为系统临时地址,所以省去了创建临时文件夹和删除文件。

具体实现如下:

1.controller层

    // 导入用户数据
	@RequiresRoles("SuperUsers")
	@PostMapping(value="/users/import")
	public ResponseEntity<Void> importUserFile(
			@RequestParam("file") MultipartFile file
	) throws Exception {
		this.userService.importUserFile(file);
		return ResponseEntity.status(HttpStatus.CREATED).build();
	}

2.service层

需要引入包

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Override
	public void importUserFile(MultipartFile mpFile) throws Exception {
	    String fileName = mpFile.getOriginalFilename(); //文件名称
	    String fileType = fileName.substring(fileName.lastIndexOf("."));//文件类型
	    InputStream file = null;
	    List<FileHeader> fileHeaders = null;
	    //上传文件为excel文件
	    if (FILE_XLS.equalsIgnoreCase(fileType) || FILE_XLSX.equalsIgnoreCase(fileType)) {
	         file = mpFile.getInputStream();
	    }else if (FILE_ZIP.equalsIgnoreCase(fileType)) {	 //上传文件为zip压缩包,包括excel文件和照片       
	        fileHeaders = zipTransfoFile(mpFile); //文件解压成list
	        for(FileHeader fileHeader : fileHeaders) {
	            String fileHeaderName = fileHeader.getFileName();
	            String fileHeaderType = fileHeaderName.substring(fileHeaderName.lastIndexOf("."));	            
	            if (FILE_XLS.equalsIgnoreCase(fileHeaderType) || FILE_XLSX.equalsIgnoreCase(fileHeaderType)) {
	                File file1 =   new File(tempStoragePath + "/" + fileHeader.getFileName());
	                FileItem fileItem = getMultipartFile(file1,file1.getName());
	                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
	                file = multipartFile.getInputStream();
	                break;
	            }
	        }	        
	       
	    }else {
	        return;
	    }
		

		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(file);
			Sheet sheet01 = wb.getSheetAt(0);
			if (sheet01 != null) {
				// 从第1行开始,跳过标题行(第0行)
				for (int curLineNo = 1; curLineNo <= sheet01.getLastRowNum(); curLineNo++) {
					Row row = sheet01.getRow(curLineNo);
					String name="";
					String dispName ="";
					String sex= "";
					String education="";
					String birthday = "";
					String email = "";
					String phone = "";
					String deptStr="";
					String roleStr="";
					String photo = null;
					String aux = null;
					String tempVal = "";
					boolean frozen = false;
					for (int colNo = 0; colNo < excelFileCols.length; colNo++) {
						Cell cell = row.getCell(colNo);
						if (cell == null) {
							continue;
						}
						cell.setCellType(Cell.CELL_TYPE_STRING);
						if (cell == null) {
							continue;
						}
						switch (excelFileCols[colNo]) {
							case "注册名":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									name = tempVal.trim();
								}
								break;
							case "姓名":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									dispName = tempVal.trim();
								}
								break;
							case "性别":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									sex = tempVal.trim();
								}
								break;
							case "学历":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									education = tempVal.trim();
								}
								break;
							case "出生日期":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									birthday = tempVal.trim();
								}
								break;
							case "邮箱":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									email = tempVal.trim();
								}
								break;
							case "电话":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									phone = tempVal.trim();
								}
								break;
							case "组织":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									deptStr = tempVal.trim();
								}
								break;
							case "角色":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									roleStr = tempVal.trim();
								}
								break;
							case "头像":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									photo = tempVal.trim();
								}
								break;
							case "附加信息":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									aux = tempVal.trim();
								}
								break;
							case "被冻结":
								tempVal = cell.getStringCellValue();
								if (tempVal != null) {
									tempVal = tempVal.trim();
									frozen = !tempVal.isEmpty() && !tempVal.equals("0");
								}
								break;
						}
					}
					if (!name.isEmpty()) {
						User user = null;
						try {
							user = this.getUserByName(name);
						} catch (java.util.NoSuchElementException e) {
							user = null;
						}
						boolean isNewUser = false;
						if (user == null) {
							isNewUser = true;
							user = new User();
						}
						user.setName(name);
						user.setDispName(dispName);

						switch (sex) {
							case "男":
								user.setSex(true);
								break;
							case "女":
								user.setSex(false);
								break;
							default:
								user.setSex(null);
								break;
						}
						switch (education) {
							case "未知":
								user.setEducation(User.EducationLevel.unkown);
								break;
							case "小学或以下":
								user.setEducation(User.EducationLevel.primarySchoolOrBelow);
								break;
							case "初中":
								user.setEducation(User.EducationLevel.juniorMidSchool);
								break;
							case "高中(中专)":
								user.setEducation(User.EducationLevel.highMidSchool);
								break;
							case "大专":
								user.setEducation(User.EducationLevel.associateCollege);
								break;
							case "本科":
								user.setEducation(User.EducationLevel.bachelor);
								break;
							case "硕士":
								user.setEducation(User.EducationLevel.master);
								break;
							case "博士及以上":
								user.setEducation(User.EducationLevel.doctorOrAbove);
								break;
							default:
								user.setEducation(null);
								break;
						}
						if (!birthday.isEmpty()) {
							SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
							user.setBirthday(format.parse(birthday));
						}
						user.setEmail(email);
						user.setPhone(phone);
						user.setFrozen(frozen);
						user.setAux(aux);
						if (isNewUser) {
							user = this.userDao.save(user);
							user.setPassword(this.genDefaultPassword(user));							
						}
						if (fileHeaders != null) {
						    for (FileHeader fileHeader : fileHeaders) {
	                            String fileHeaderName = fileHeader.getFileName();
	                            if (fileHeaderName.equals(photo)) {
	                                File file1 =   new File(tempStoragePath + "/" + fileHeader.getFileName());
	                                FileItem fileItem = getMultipartFile(file1,file1.getName());
	                                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);                               
	                                addUserPhoto(user,multipartFile);
	                                break;
	                            }
	                        } 
						}
											
					}
				}
			}
		}
		finally {
			wb.close();
			file.close();
		}
	}
 private List<FileHeader> zipTransfoFile(MultipartFile mpFile) throws Exception {
        String fileName = mpFile.getOriginalFilename();
        //String path = "E:/tempZip";
        File file = new File(tempStoragePath + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        mpFile.transferTo(file);
        ZipFile zipFile = new ZipFile(file);
        zipFile.setFileNameCharset("utf-8");
        //String dest = "E:/tempZip";
        File destFile = new File(tempStoragePath);
        zipFile.extractAll(tempStoragePath);

        return zipFile.getFileHeaders();
    }

         /**
	     * 将file转换成fileItem
	     * @param file
	     * @param fieldName
	     * @return
	     */
	    private FileItem  getMultipartFile(File file, String fieldName){
	        FileItemFactory factory = new DiskFileItemFactory(16, null);
	        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        try {
	            FileInputStream fis = new FileInputStream(file);
	            OutputStream os = item.getOutputStream();
	            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
	                os.write(buffer, 0, bytesRead);
	            }
	            os.close();
	            fis.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return item;
	    }

@Override
	public String addUserPhoto(User user, MultipartFile file) throws Exception {
        //如果文件不为空,写入上传路径
        if (!file.isEmpty()) {
        	String path = this.userPhotoSavePath;//"E:/dd";
            //上传文件名
            String filename = user.getId() + /*"__" + (new Date()).getTime()+*/  "__" +  file.getOriginalFilename();
            File filepath = new File(path, filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
			File newFile = new File(path + File.separator + filename);
            file.transferTo(newFile);
            String originFileName = user.getPhoto();
            user.setPhoto(filename);
			byte[] ff = this.extractFaceFeatures(newFile);
			user.setFacefeature(ff);
			// 将旧头像文件删除掉 2021.05.30添加
			if (originFileName != null && !originFileName.isEmpty()) {
				try {
					java.io.File originFileObj = new java.io.File(path + java.io.File.separator + originFileName);
					if (originFileObj.exists() && !originFileObj.isDirectory()) {
						originFileObj.delete();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			this.faceFeatureLastTimeVersion = (new Date()).getTime();
			return filename;
        } else {
            throw new CustomException(HttpStatus.BAD_REQUEST);
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中解压zip文件并循环导入Excel数据可以通过以下步骤实现: 首先,需要使用JavaZipInputStream类来解压zip文件。可以使用FileInputStream类来读取zip文件,然后通过ZipInputStream类逐个读取zip中的条目。可以使用ZipEntry类获取条目的名称,并使用ZipInputStream类的getNextEntry()方法将输入流的位置移动到下一个条目。 然后,需要使用Java的Apache POI库来读取和操作Excel文件。可以使用Workbook类来打开和读取Excel文件,可以根据需要选择使用HSSFWorkbook(用于处理旧版本的Excel文件)或XSSFWorkbook(用于处理最新版本的Excel文件)。可以使用Sheet类来获取工作簿中的工作表,使用Row类来获取行,并使用Cell类来获取单元格。 在循环过程中,可以通过ZipEntry类判断解压缩的条目是否为Excel文件。如果是Excel文件,则可以根据需要使用Workbook类打开并读取该文件。然后,可以使用Sheet类获取工作簿中的工作表。通过循环遍历行和单元格,可以逐行逐列地读取和处理Excel数据。 最后,根据需要对读取的Excel数据进行处理和存储,可以将其保存到数据库中或导出到其他文件格式中。 需要注意的是,解压和读取大型zip文件Excel文件可能会消耗较多的内存和时间。因此,建议在处理大型文件时使用适当的缓存和优化策略,以提高性能和效率。 总结来说,使用JavaZipInputStream类解压zip文件,并使用Apache POI库读取和处理Excel数据,能够很方便地实现解压zip文件并循环导入Excel数据的功能

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值