1.jsp中代码
3.controller中代码
@RequestMapping("/upFile.do")
@ResponseBody
public ModelAndView Upload(HttpServletRequest request, HttpServletResponse response) {
logger.info("===============批量上传业务处理开始=================");
ResultDTO resultDTO = new ResultDTO();
// 封转返回页面和数据
ModelAndView modelAndView = new ModelAndView();
// 创建一个通用的多部分解析器.
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 设置编码
commonsMultipartResolver.setDefaultEncoding("gbk");
// 判断 request 是否有文件上传,即多部分请求...
if (commonsMultipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);
// file 是指 文件上传标签的 name=值
// 根据 name 获取上传的文件...
MultipartFile file = multipartRequest.getFile("file1");
String fileName = null;
InputStream ins = null;
try {
fileName = file.getOriginalFilename();
String fileExtends = fileName.split("\\.")[fileName.split("\\.").length - 1];
if (!"xls".equals(fileExtends)) {
logger.error("必须上传 .xls 格式的Excel文件");
throw new BusinessException("必须上传 .xls 格式的Excel文件");
}
ins = file.getInputStream();
String flag = trainingScheduleService.upload(ins, fileName);
modelAndView.addObject("text", flag);
modelAndView.setViewName("/schedule/scheduleError");
} catch (BusinessException e) {
modelAndView.addObject("text", e.getMessage());
modelAndView.setViewName("/schedule/scheduleError");
logger.error(e.getMessage());
} catch (IOException e) {
modelAndView.addObject("text", "处理文件失败");
modelAndView.setViewName("/schedule/scheduleError");
e.printStackTrace();
} catch (Exception e) {
modelAndView.addObject("text", "处理文件失败");
modelAndView.setViewName("/schedule/scheduleError");
e.printStackTrace();
} finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
}
logger.info("================批量上传业务处理结束==============");
return modelAndView;
}
4.ServiceImpl中代码
public String upload(InputStream ins, String fileName) throws Exception {
InputStream sbs = null;
Workbook book = null;
// String batchNo = null;
try {
String userId = SessionUtil.getUser().getUserId();
// String userId =
// manageUserService.getCurrentUserInfo().getUserId();
logger.info("当前操作用户为:" + userId);
byte[] b = null;
try {
b = toByteArray(ins);
} catch (Exception e) {
e.printStackTrace();
} // 把流转换为数组
logger.info("Excel文件已经保存到本地磁盘中");
// batchNo = "B" + DateUtil.getCurrentDate("yyyyMMddHHmmsssss");
// 保存文件
saveFile(b, fileName);
TrainingSchedule trainingSchedule = new TrainingSchedule();
// trainingSchedule.setTransNo(batchNo);
// trainingSchedule.setFileName(fileName);
trainingSchedule.setCreateUser(userId);
trainingSchedule.setCreateDate(DateUtil.getCurrentDateTime());
sbs = new ByteArrayInputStream(b);
try {
book = Workbook.getWorkbook(sbs);
} catch (BiffException e) {
e.printStackTrace();
}
// 打开文件
Sheet sheet = book.getSheet(0);
for (int i = 1; i < sheet.getRows(); i++) {
// 从Excel中取出信息
String serialNumber = sheet.getCell(0, i).getContents().trim(); // 编号
if (serialNumber == null || "".equals(serialNumber.trim())) {
throw new BusinessException("请确认上传文件与模板Excel文件格式一致!");
}
String annual = sheet.getCell(1, i).getContents().trim();
String manage_com = sheet.getCell(2, i).getContents().trim();
String class_type = sheet.getCell(3, i).getContents().trim();
String annual_target = sheet.getCell(4, i).getContents().trim();
// 上传重复的文件,先查询是否有这个文件,有的话就会将之前的文件进行覆盖,将之前的数据状态改为“无效”
TrainingScheduleExample example = new TrainingScheduleExample();
TrainingScheduleExample.Criteria criteria = example.createCriteria();
criteria.andAnnualEqualTo(annual).andManageComEqualTo(manage_com).andClassTypeEqualTo(class_type)
.andScheduleStateEqualTo("1");
List
if (list != null) {
for (int j = 0; j < list.size(); j++) {
TrainingSchedule trainingSchedule1 = list.get(j);
trainingSchedule1.setScheduleState("0");
trainingScheduleMapper.updateByPrimaryKey(trainingSchedule1);
}
}
trainingSchedule.setAnnual(annual);
trainingSchedule.setManageCom(manage_com);
trainingSchedule.setClassType(class_type);
trainingSchedule.setAnnualTarget(annual_target);
trainingSchedule.setCreateUser(userId);
trainingSchedule.setCreateDate(DateUtil.getCurrentDateTime());
trainingSchedule.setScheduleState("1"); // 初始值默认为有效;
// 对manage_com与class_type两个字段进行数据校验
verifyData(trainingSchedule, serialNumber) ;
// 数据校验通过后才可以保存明细和保存数据库还有本地磁盘
trainingScheduleMapper.insert(trainingSchedule);
logger.info("Excel内容明细已经保存到数据库中");
}
// trainingScheduleMapper.insert(anhuiSelfcard);
} catch (IOException e) {
} catch (BusinessException e) {
throw new BusinessException(e.getMessage());
} finally {
try {
sbs.close();
} catch (IOException e) {
logger.info("文件流关闭异常!");
e.printStackTrace();
}
try {
book.close();
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("批量上传文件解析失败!");
}
}
return "上传成功!";
}
数据校验代码
private void verifyData(TrainingSchedule trainingSchedule, String serialNumber) {
logger.info("********************数据合法性校验,接收参数:" + trainingSchedule);
String manageCom = trainingSchedule.getManageCom();
String classType = trainingSchedule.getClassType();
DefCodeInfoExample example = new DefCodeInfoExample();
DefCodeInfoExample.Criteria criteria = example.createCriteria();
criteria.andCodeEqualTo(classType).andCodeTypeEqualTo("class_type");
List
if (list.size() == 0) {
throw new BusinessException("类型为" + classType + " 的数据不存在!上传失败!");
} else {
ManagecomInfoExample example1 = new ManagecomInfoExample();
ManagecomInfoExample.Criteria criteria1 = example1.createCriteria();
criteria1.andManageComEqualTo(manageCom);
List
if (list1.size() == 0) {
throw new BusinessException("机构为" + manageCom + " 的机构不存在!上传失败!");
}
}
}
}