controller层
/**
* 导入excel模板
* */
@RequestMapping(value = "/importmoban", method = RequestMethod.POST)
@ResponseBody
public Map importmoban(MultipartFile uploadfile,@ModelAttribute ActivitiesBean bean, HttpServletResponse response,HttpServletRequest request) throws IOException {
try {
String attachPath = request.getSession().getServletContext().getRealPath("/muban");
String name=uploadfile.getOriginalFilename();
String path=attachPath+File.separator+name;
File file= new File(path);
uploadfile.transferTo(file);
return activitiesService.importmoban(file, bean);
} catch (IOException e) {
Map map = new HashMap();
map.put("returnMess", "导入失败!");
return map;
}
}
service层
public Map importmoban(File file,ActivitiesBean bean);
serviceImpl层
@Override
public Map importmoban(File uploadfile,ActivitiesBean bean){
Map resultMap = new HashMap();
List planList = new ArrayList();
int errRownum = 0;
try {
Workbook workBook = null;
try {
workBook = new XSSFWorkbook(new FileInputStream(uploadfile));// 支持xlsx
} catch (Exception ex) {
workBook = new HSSFWorkbook(new FileInputStream(uploadfile));// 支持 xls
}
NumberFormat numberFormat = NumberFormat.getInstance();// 创建一个数值格式化对象
numberFormat.setMaximumFractionDigits(2);// 设置精确到小数点后2位
for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workBook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
//标题行
Row titleRow = sheet.getRow(1);
// 循环行Row
for (int rowNum = 4; rowNum 0) {
for (ActivitiesBean c : planList) {
activitiesBeanMapper.addActivities(c);
successRow++;
}
}else {
resultMap.put("returnMess", "未读取到数据!");
return resultMap;
}
FileTool.delFile(uploadfile);// 删除临时目录下的excel文件
resultMap.put("returnMess", "成功导入数据(共" + successRow + "条)!");
return resultMap;
} catch (Exception e) {
resultMap.put("returnMess", new StringBuffer("第").append(errRownum+1).append("行数据有误!").toString());
return resultMap;
}
}
/**
* 删除已经存在的文件
*
* @param filePathAndName
* 文件存放路径
*/
public static void delFile(File file) {
try {
if (file.exists()) {
file.delete();
}
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
