上传Excel文件并读取存入数据库

备注:接上篇点击打开链接


1、controller层方法:

	@RequestMapping(value = "uploadFile")
	public void uploadFile(Model model, MultipartFile file) throws Exception {
		bluetoothService.uploadFileToDatabase(file);
		model.addAttribute(new Protocol());
	}


2、service实现层方法:


	public void uploadFileToDatabase(MultipartFile file) {
		// TODO Auto-generated method stub
		if (file == null) {
			throw new BusinessException(ResponseCode.FAIL.code, "文件为空!");
		}
		String fileName = file.getOriginalFilename();
		if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
			logger.error("文件{}格式不对,仅支持Excel文件!", fileName);
			throw new BusinessException(ResponseCode.FAIL.code, "文件格式不对,仅支持Excel文件!");
		}
		
		XSSFWorkbook workBook = null;
		try {
			InputStream input = file.getInputStream();
			workBook = new XSSFWorkbook(input);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("===>>文件" + fileName + "异常:" + e.getMessage(), e);
			throw new BusinessException(ResponseCode.FAIL.code, "文件上传异常:" + e.getMessage());
		}
		XSSFSheet sheet = workBook.getSheetAt(0);
		if (sheet != null) {
			int rows = sheet.getPhysicalNumberOfRows();
			for (int i = 1; i < rows; i++) {
				XSSFRow row = sheet.getRow(i);
				for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
					XSSFCell cell = row.getCell(j);
					String cellStr = "";
					if (cell != null) {
						cellStr = cell.toString();
					}
					System.out.print("【" + cellStr + "】 ");
				}
				
				System.out.println();
			}
		}
	}


注意:spring配置文件:applicationContext.xml增加配置



         
        
    


你可能感兴趣的:(JAVA,SpringMVC)