POI實現數據從Excel導入到數據庫中例子

利用POI從EXCEL導入數據也是我第一次操作,第一次都是很痛苦的,況且公司人也沒誰用過。下面一起來順一遍吧:

1、首先數據的錄入必須按照模板裏面的要求;

2、我們實現的過程分3步:文件的上傳------>數據保存到數據庫------>刪除上傳的文件

3、模板存放文件位置,根據自己來定,參考如下:

4、參考模板如下


5、文件的上傳用的fileupload,需要兩個jar包(點擊下載)

6、主要代碼如下:

      <1>文件的上傳 和 刪除上傳文件操作

/**
	 * 導入之前的上傳操作
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@POST
	@Path("/userImportUpload")
	@Produces("*/*")
	public String userImportUpload(){
		System.out.println("********************************************************************");
		Message message = PhaseInterceptorChain.getCurrentMessage();
		HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
		String uploadPath = request.getServletContext().getRealPath("/") + "\\make\\";
		File userXmlUP = new File(uploadPath + "upload\\");
		if (!userXmlUP.exists()) {
			userXmlUP.mkdirs();
		}
		try {
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setHeaderEncoding("utf-8");
			List<FileItem> fileList = upload.parseRequest(request);
			Iterator<FileItem> it = fileList.iterator();
			String name = "";//上傳組件的名字
			String extName = "";//上傳組件的後綴名
			while (it.hasNext()) {
				FileItem item = it.next();
				name = item.getName();
				//System.out.println("上傳組件的名字:"+ name);
				//擴展名格式  
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				if (!item.isFormField()) {//判斷是否是上傳組件true代表不是上傳組件
					InputStream is = item.getInputStream();//得到流
					name = item.getName();//上傳組件名字
					FileOutputStream fos = new FileOutputStream(new File(uploadPath + "upload\\","user" + extName));//user.xml
					byte[] b = new byte[1024];
					int len = -1;
					while((len = is.read(b)) != -1){
						fos.write(b, 0, len);
						fos.flush();
					}
					fos.close();
					is.close();
				}
				String templatePath = request.getServletContext().getRealPath("/") + "\\make\\upload\\";
				File f = null;
				if(extName.equalsIgnoreCase(".xls")){
					f = new File(templatePath+"user.xls");
				}
				if(extName.equalsIgnoreCase(".xlsx")){
					f = new File(templatePath+"user.xls");
				}
				String loginAccount = (String) request.getSession().getAttribute("account");//登陸者賬號
				//執行導入操作
				saveXlsToDB(f,loginAccount,request);
				//操作完成後刪除指定目錄和文件
				File dd = new File(templatePath);
				File[] listFiles = dd.listFiles();
				for(File fl : listFiles){
					fl.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error!";
		}
		return "success!";
	}

      <2>數據保存到數據庫

/**
	 * 完成將XML文件內容保存到數據庫 
	 * @param f
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private void saveXlsToDB(File f,String loginAccount,HttpServletRequest request) throws IOException, FileNotFoundException {
		HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(f));
		//打開一個工作表
		HSSFSheet sheet = wb.getSheetAt(0);
		HSSFRow nRow = null;
		HSSFCell nCell = null;
		int rowNumSum = sheet.getLastRowNum()+1;//總行數,是從0開始的,循環條件<總行數
		int colNo = 1;//列號 應爲模板中第一列是空白列
		User user = new User();
		String importAccount = null;//xml中賬號內容
		for(int i = 2;i<rowNumSum;i++){
			colNo = 1;
			nRow = sheet.getRow(i);//第三行
			colNo++;//跳過一列
			
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			importAccount = nCell.getStringCellValue();
			user.setAccount(importAccount);//賬號
			
			nCell = nRow.getCell(colNo++);
			user.setName(nCell.getStringCellValue());//姓名
			colNo++;//跳過一列
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setGender(Integer.parseInt(nCell.getStringCellValue()));//性別標識
			colNo++;//跳過一列
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setJobTitle(Integer.parseInt(nCell.getStringCellValue()));//職稱標識
			colNo++;//跳過一列
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setType(Integer.parseInt(nCell.getStringCellValue()));//角色標識
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setBirthDate(nCell.getStringCellValue());//出生日期
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setLandlineNumber(nCell.getStringCellValue());//座機號碼
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setCellPhoneNumber(nCell.getStringCellValue());//手機號碼
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setEmail(nCell.getStringCellValue());//電子郵箱
			nCell = nRow.getCell(colNo++);
			nCell.setCellType(Cell.CELL_TYPE_STRING);
			user.setPostCode(nCell.getStringCellValue());//郵編
			nCell = nRow.getCell(colNo++);
			user.setAddress(nCell.getStringCellValue());//地址
			nCell = nRow.getCell(colNo++);
			user.setIntroduction(nCell.getStringCellValue());//簡介
			nCell = nRow.getCell(colNo++);
			user.setRemark(nCell.getStringCellValue());//備註
		}
		//設置初始密碼
		final Properties pro = constantProperties(request);
		user.setPassword(pro.getProperty("constant.defaultPassword"));
		//user.setPassword("123456");//密碼默認爲123456 ,一會將起放入到配置文件中
		user.setDeleteFlag(0);
		if(loginAccount.equalsIgnoreCase(mr.getMessage("admin.name"))){
			user.setCreateUserId(0);
		}else{
			user.setCreateUserId(userService.getAccount(loginAccount).getId());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String createDateStr = sdf.format(new Date());// 獲取當前日期
		user.setCreateDate(createDateStr);
		if(userService.getByCode(importAccount)){//當導入的數據的account不存在時執行添加方法
			userService.save(user);
		}else{//如果已經存在改account則進行修改操作
			user.setId(userService.getAccount(importAccount).getId());
			userService.update(user);
		}
	}

 7、導入按鈕

<a href="#" class="but_tj3">導入</a>

8、點擊確定按鈕完成操作,提交表單!

注:上邊操作針對的是2003版本的,對於2007版本的所有的HSSF*換成XSSF*即可,前提jar包得支持!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章