1.在页面中点击事件弹出模态框
/*文件的导入*/
$(".btn-import").click(function () {
$("#xlsModal").modal("show");
});
2.弹出模态框后点击保存进行提交
$("#editForm").ajaxForm(function (ret) {
if(ret.flag==true){
$.messager.alert("温馨提示:",ret.msg);
//window.location.reload();
}else{
let fallEmpList=[];
$(ret.data).each(function (i,e) {
fallEmpList.push(e.name);
});
$.messager.alert("温馨提示:",ret.msg+"<br>"+fallEmpList);
}
});
3.模态框
<div class="modal fade" id="xlsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">导入</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="/employee/importXls.do" enctype="multipart/form-data" method="post" id="editForm">
<input type="hidden" name="id">
<div class="form-group" style="margin-top: 10px;">
<label for="name" class="col-sm-3 control-label"></label>
<div class="col-sm-6">
<input type="file" name="file" accept="application/vnd.ms-excel">
</div>
</div>
<div class="form-group" style="margin-top: 10px;">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<a href="/xls/employeeTemplate.xls" class="btn btn-success" >
<span class="glyphicon glyphicon-download"></span> 下载模板
</a>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="submit" form="editForm" class="btn btn-primary btn-submit">保存</button>
</div>
</div>
</div>
</div>
4.controller
@RequestMapping("/importXls")
@ResponseBody
public ResultBean importXls(MultipartFile file) throws IOException {
List<Employee> successList = new ArrayList<>();
List<Employee> failList = new ArrayList<>();
HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
HSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 2; i < rows; i++) {
HSSFRow row = sheet.getRow(i);
Employee employee = new Employee();
try {
employee.setPassword("1");
HSSFCell cell2 = row.getCell(2);
employee.setName(cell2.getStringCellValue());
HSSFCell cell3 = row.getCell(3);
employee.setEmail(cell3.getStringCellValue());
HSSFCell cell4 = row.getCell(4);
employee.setAge((int)cell4.getNumericCellValue());
HSSFCell cell5 = row.getCell(5);
employee.setAdmin("是".equals(cell5.getStringCellValue()));
HSSFCell cell6 = row.getCell(6);
String departName = cell6.getStringCellValue();
Department department = departmentService.selectByName(departName);
employee.setDept(department);
employeeService.save(employee);
successList.add(employee);
}catch (Exception e){
e.printStackTrace();
failList.add(employee);
}
}
wb.close();
if(failList.size()>0){
return ResultBean.fail("导入失败,成功数量:"+successList.size()+",失败数量:"+failList.size(),failList);
}else {
return ResultBean.success("导入成功,导入数量"+successList.size());
}
}