功能描述:
只导入用户信息文件,文件为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);
}
}