SSM框架poi导入导出Excel(MySQL)

Excel导入的MySQL的方法:

浏览器选择excel文件,传至服务端,在服务端解析此excel并将数据导入到数据库中。

源码下载

这里只保存关键代码,详细的源代码可点击上面源码下载前往下载

1,项目结构:

SSM框架poi导入导出Excel(MySQL)_第1张图片

2,导入页面:

jsp:

js:

function uploadFile() {
			var file = $("#upload").val();
			file = file.substring(file.lastIndexOf('.'), file.length);
			if (file == '') {
				alert("上传文件不能为空!");
			} else if (file != '.xlsx' && file != '.xls') {
				alert("请选择正确的excel类型文件!");
			} else {
				ajaxFileUpload();
			}
		}
		function ajaxFileUpload() {

			var formData = new FormData();
			var name = $("#upload").val();
			formData.append("file", $("#upload")[0].files[0]);
			formData.append("name", name);
			$.ajax({
				url : "excel/InputExcel.do",
				type : "POST",
				async : false,
				data : formData,
				processData : false,
				contentType : false,
				beforeSend : function() {
					console.log("正在进行,请稍候");
				},
				success : function(e) {
					if (e == "01") {
						alert("导入成功");
					} else {
						alert("导入失败");
					}
				}
			});
		}

		function OutputExce() {
			window.location.href = "/ExcelDemo/excel/OutputExcel.do";
		}

3,服务端解析处理Excel文件:

Controller:

@RequestMapping(value = "/InputExcel.do")
	@ResponseBody
	public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
		String flag = "02";// 上传标志
		if (!file.isEmpty()) {
			try {
				String originalFilename = file.getOriginalFilename();// 原文件名字
				log.info("文件名:" + originalFilename);
				InputStream is = file.getInputStream();// 获取输入流
				flag = excelService.InputExcel(is, originalFilename);
			} catch (Exception e) {
				flag = "03";// 上传出错
				e.printStackTrace();
			}
		}
		return flag;
	}
	
	@RequestMapping(value = "/OutputExcel.do", produces = "application/form-data; charset=utf-8")
	@ResponseBody
	public String OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html,charset=utf-8");

		List list = excelService.OutputExcel();

		String message = OutputExcel.OutExcel(request, response, list);
		if (message.equals("fail")) {
			ServletOutputStream out = response.getOutputStream();
			message = "导出失败,请重试";
			String s = "";
			out.print(s);
		}
		return null;
	}

service:

        @Override
	public String InputExcel(InputStream is, String originalFilename) {
		Map ginsengMap = new HashMap();
		List> list;
		if (originalFilename.endsWith(".xls")) {
			list = Excel.readExcel2003(is);
		} else {
			list = Excel.readExcel2007(is);
		}
		for (int i=0,j=list.size();i row = list.get(i);
			ginsengMap.put("name", row.get(0).toString());
			ginsengMap.put("sex", row.get(1).toString());
	        ginsengMap.put("email", row.get(2).toString());
	        ginsengMap.put("dept_id", row.get(3).toString());
	        excelMapper.InputExcel(ginsengMap);
		}
		return "01";
	}

	@Override
	public List OutputExcel() {
		return excelMapper.getAll();
	}

mapper.xml:




	
		
		
		
		
		
	

	
		
		
		
		
		
		
		
			
			
		
	

	
		insert into wei.emp_t (name,sex,email,dept_id) values
		(#{name },#{sex },#{email },#{dept_id },)
	

	
		e.id, e.name, e.sex, e.email, e.dept_id, d.d_id, d.d_name
	

	
		
			
				
					
						
							
								
									and ${criterion.condition}
								
								
									and ${criterion.condition} #{criterion.value}
								
								
									and ${criterion.condition} #{criterion.value} and
									#{criterion.secondValue}
								
								
									and ${criterion.condition}
									
										#{listItem}
									
								
							
						
					
				
			
		
	

	

4,解析excel的工具类:

excel文件传至服务端:

public static String upload(HttpServletRequest request, HttpServletResponse response) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(MAX_REQUEST_SIZE);
		upload.setHeaderEncoding("UTF-8");
		String uploadPath = request.getSession().getServletContext().getRealPath("/") + UPLOAD_DIRECTORY;
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		try {
			@SuppressWarnings("unchecked")
			List formItems = upload.parseRequest(request);
			if (formItems != null && formItems.size() > 0) {
				for (FileItem item : formItems) {
					if (!item.isFormField()) {
						String fileName = new File(item.getName()).getName();
						filePath = uploadPath + File.separator + fileName;
						File storeFile = new File(filePath);
						item.write(storeFile);
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return filePath;
	}

读取Excel文件:

public static ArrayList> readExcel2003(InputStream is) {
		try {
			ArrayList> rowList = new ArrayList>();
			ArrayList colList;
			HSSFWorkbook wb = new HSSFWorkbook(is);
			HSSFSheet sheet = wb.getSheetAt(0);
			HSSFRow row;
			HSSFCell cell;
			Object value = null;
			for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
				row = sheet.getRow(i);
				colList = new ArrayList();
				if (row == null) {
					if (i != sheet.getPhysicalNumberOfRows()) {// 判断是否是最后一行
						rowList.add(colList);
					}
					return rowList;
				} else {
					rowCount++;
				}
				for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
					cell = row.getCell(j);
					if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
						if (j != row.getLastCellNum()) {
							colList.add("");
						}
						continue;
					}
					if (null != cell) {
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC:
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
								break;
							} else {
								Double d = cell.getNumericCellValue();
								DecimalFormat df = new DecimalFormat("#.##");
								value = df.format(d);
							}
							break;
						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue();
							break;
						case HSSFCell.CELL_TYPE_BOOLEAN:
							value = cell.getBooleanCellValue() + "";
							break;
						case HSSFCell.CELL_TYPE_FORMULA:
							value = cell.getCellFormula() + "";
							break;
						case HSSFCell.CELL_TYPE_BLANK:
							value = "";
							break;
						case HSSFCell.CELL_TYPE_ERROR:
							value = "非法字符";
							break;
						default:
							value = "未知类型";
							break;
						}

					}
					colList.add(value);
				}
				rowList.add(colList);
			}
			if (is != null) {
				is.close();
			}
			return rowList;
		} catch (Exception e) {
			return null;
		}
	}

	public static ArrayList> readExcel2007(InputStream is) {
		try {
			ArrayList> rowList = new ArrayList>();
			ArrayList colList;
			XSSFWorkbook wb = new XSSFWorkbook(is);
			XSSFSheet sheet = wb.getSheetAt(0);
			XSSFRow row;
			XSSFCell cell;
			Object value = null;

			for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
				row = sheet.getRow(i);
				colList = new ArrayList();
				if (row == null) {
					if (i != sheet.getPhysicalNumberOfRows()) {
						rowList.add(colList);
					}
					return rowList;
				} else {
					rowCount++;
				}
				for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
					cell = row.getCell(j);
					if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
						if (j != row.getLastCellNum()) {
							colList.add("");
						}
						continue;
					}

					if (null != cell) {
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC:
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
								break;
							} else {
								Double d = cell.getNumericCellValue();
								DecimalFormat df = new DecimalFormat("#.##");
								value = df.format(d);
							}
							break;

						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue();
							break;

						case HSSFCell.CELL_TYPE_BOOLEAN:
							value = cell.getBooleanCellValue() + "";
							break;

						case HSSFCell.CELL_TYPE_FORMULA:
							value = cell.getCellFormula() + "";
							break;

						case HSSFCell.CELL_TYPE_BLANK:
							value = "";
							break;

						case HSSFCell.CELL_TYPE_ERROR:
							value = "非法字符";
							break;

						default:
							value = "未知类型";
							break;
						}

					}
					colList.add(value);
				}
				rowList.add(colList);
			}
			if (is != null) {
				is.close();
			}
			return rowList;
		} catch (Exception e) {
			System.out.println("exception");
			return null;
		}
	}
 
  

导出数据到excel并在浏览器下载:

public static String OutExcel(HttpServletRequest request, HttpServletResponse response, List list) throws Exception {

		String message = "fail";
		String dir = request.getSession().getServletContext().getRealPath("/output");
		File fileLocation = new File(dir);
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
			if (!isCreated) {
			}
		}
		String webUrl = request.getSession().getServletContext().getRealPath("/output");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd mm-ss");
		String createExcelname = df.format(new Date()) + "OutputExcel.xls";
		String outputFile = webUrl + File.separator + createExcelname;
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, "emp");
		HSSFRow row1 = sheet.createRow(0);
		HSSFCell cell0 = row1.createCell(0, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell1 = row1.createCell(1, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell2 = row1.createCell(2, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell3 = row1.createCell(3, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell4 = row1.createCell(4, HSSFCell.CELL_TYPE_STRING);
		
		cell0.setCellValue("id");
		cell1.setCellValue("name");
		cell2.setCellValue("sex");
		cell3.setCellValue("email");
		cell4.setCellValue("dept_id");
		response.setContentType("text/html;charset=UTF-8");

		for (int j = 0; j < list.size(); j++) {
			
			EmpT empt = new EmpT();
			empt = list.get(j);
			
			HSSFRow row = sheet.createRow(j + 1);
			HSSFCell c0 = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c1 = row.createCell(1, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c2 = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c3 = row.createCell(3, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c4 = row.createCell(4, HSSFCell.CELL_TYPE_STRING);

			c0.setCellValue(empt.getId());
			c1.setCellValue(empt.getName());
			c2.setCellValue(empt.getSex());
			c3.setCellValue(empt.getEmail());
			c4.setCellValue(empt.getDeptName().getdName());
		}
		FileOutputStream fOut = new FileOutputStream(outputFile);
		workbook.write(fOut);
		fOut.flush();
		fOut.close();
		File f = new File(outputFile);
		if (f.exists() && f.isFile()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				URLEncoder.encode(f.getName(), "utf-8");
				byte[] b = new byte[fis.available()];
				fis.read(b);
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment; filename=" + createExcelname + "");
				ServletOutputStream out = response.getOutputStream();
				out.write(b);
				out.flush();
				out.close();
				if (fis != null) {
					fis.close();
				}
				f.delete();
				message = "success";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return message;
	}

5,关键代码到此完成,运行一下看看:

选择excel导入,服务端就会将excel中的数据读取插入到数据库中,

Excel文件:

SSM框架poi导入导出Excel(MySQL)_第2张图片

数据库:

SSM框架poi导入导出Excel(MySQL)_第3张图片

项目结束,excel文件数据成功导入的数据库中。

获取更多教程,请持续关注我的博客。

你可能感兴趣的:(java)