(1)前端:
<form enctype="multipart/form-data" method="post" action="/xx/xx">
文件:<input type="file" name="fileUpload" style="width: 200px" />
<input type="submit" value="导入xls数据" />
</form>
注意这种展示效果比较丑,做好封装在绚丽的弹框中使用。
(2)后端:
@RequestMapping("/xx/xx")
public String importCallerInfo(MultipartFile fileUpload, HttpSession session)throws Exception{
if(!fileUpload.isEmpty()){
int flag = aaService.importCallerInfo(fileUpload, session);
if (flag==-1){
return "redirect:/";
}
}
//如果上传文件为空,跳转到导入原页面。
return "redirect:/xx/xx/xx.html";
}
public int importCallerInfo(MultipartFile fileUpload, HttpSession httpSession)throws Exception {
LoginUser user = (LoginUser) httpSession.getAttribute("user_id");
if(user==null){
return -1;
}
String fileName = fileUpload.getOriginalFilename();
File uploadFilePathTmp = new File(uploadFilePath);
if (!uploadFilePathTmp.exists()) {
uploadFilePathTmp.mkdirs();
}
String filePath = uploadFilePath + File.separator + fileName;
long temp=0;
try {
fileUpload.transferTo(new File(filePath));
FileInputStream fileInputStream = new FileInputStream(filePath);
Workbook sheets = new HSSFWorkbook(fileInputStream);
Sheet sheet = sheets.getSheetAt(0);
List<Entity> list = new ArrayList<>();
for (Row row : sheet) {
// if(row.getRowNum()==0){
// continue;
// }
//为空的行不解析
if(row.getCell(0)==null||row.getCell(0).equals("")){
continue;
}
Entity entity = new Entity();
entity.setId(UUID.randomUUID().toString().replace("-",""));
entity.setInsert_time(sdf2.format(new Date()));
entity.setInsert_user(user.getUsername());
temp++;
for (Cell cell : row) {
cell.setCellType(CellType.STRING);
String str=cell.getStringCellValue();
int columnIndex = cell.getColumnIndex();
switch (columnIndex){
case 0:
entity.setAttr01(str);
break;
case 1:
entity.setAttr02(str);
break;
case 2:
entity.setAttr03(str);
break;
case 3:
entity.setAttr04(str);
break;
}
}
list.add(entity);
//2000条批量插入数据库一次
if(temp%2000==0){
int i = xDao.betchInsert(list);
list.clear();
}
}
int i = xDao.betchInsert(list);
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}