您当前的位置: 首页 >  Java

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java导入excel模板例子

小志的博客 发布时间:2018-12-29 13:35:35 ,浏览量:0

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();
        }
    }

在这里插入图片描述

关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.0523s