poi를 이용하여 excel에서 데이터를 데이터베이스로 가져오기

11095 단어
최근에 excel에서 데이터베이스로 데이터를 가져오는 상황이 발생하여 POI 기술을 이용하여 데이터 가져오기를 실현하였다.
프런트 페이지 코드는 다음과 같습니다.
<input type="file" name="" id="file" style="width: 165px">
<button type="button" onclick="improtMessage()" style="width: 48px">  </button>
<button type="button" onclick="exportMessage()" style="width: 48px">  </button>
<button type="button" onclick="dowloadMessage()" style="width: 70px">    </button>

프론트 데스크톱 js 코드:
/**
 *     
 */
function improtMessage() {
	$.messager.confirm('  ','        ?',function(r){
		if (r){
			var fileName=$('#file').val();
			var file=fileName.split(".")[0];
		
			$('#file').attr("name",$('#file').val());
			$.ajaxFileUpload({
				url: path+'/systemConfigureController/importSysConfig.do',
				secureuri: false,//  
				fileElementId: 'file',//    ID
				dataType: 'text',//         
				success: function(data){
					$.messager.alert('  ','      !');
					if(file == "  "){
						selectVillageMessage();						
					}if(file == "     "){
						selectCountryMessage();					
					}if(file == "   "){
						selectPositionMessage();					
					}if(file == "    "){
						selectIMEIMessage();					
					}
				}
			})
		}
	});
}

제어 레이어 코드는 다음과 같습니다.
/**
	 *     
	 * @param request
	 * @param response
	 * @throws IOException
	 */

	@RequestMapping("importSysConfig")
	public void importData(HttpServletRequest request, HttpServletResponse response) throws IOException{
		logger.info("**********into method importData*************");
		//      
	    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
	        request.getSession().getServletContext());
	    //   form   enctype="multipart/form-data"
	    if (multipartResolver.isMultipart(request)) {
	    	MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	    	Iterator<String> iter = multiRequest.getFileNames();
	    	while (iter.hasNext()) {
	    		List objList = new ArrayList();
	    		MultipartFile file = multiRequest.getFile(iter.next());
	    		logger.info("print out file:  "+file+"  fileName:  "+file.getName()+" fileSize: "+file.getSize());
    			version = (file.getName().endsWith(".xls") ? version2003 : version2007);
    			if (version == 2003) {
    				 POIFSFileSystem fs = new POIFSFileSystem(file.getInputStream());  
                     HSSFWorkbook wb = new HSSFWorkbook(fs);  
                     HSSFSheet sheet = wb.getSheetAt(0); 
                     readObject(file.getName(), sheet);
                     logger.info("print out readExcel: " + objList);
    			}else if (version == 2007){
    				XSSFWorkbook hwk = new XSSFWorkbook(file.getInputStream());//  is       excel  
    				XSSFSheet sheet = hwk.getSheetAt(0);//   book      sheet
    				readObject(file.getName(), sheet);
    				logger.info("print out readExcel: " + objList);
    			}
	    	}
	    }
	    response.getWriter().print("1");

	}
	
	/**
	 *      excle  ,         
	 * @param name
	 * @param sheet
	 * @return
	 */
	public void readObject(String name, Sheet sheet){
		List objList = new ArrayList();
		String _name = name.substring(0, name.indexOf("."));
		if (_name.equals("     ")){
			objList = readCountryExcel(sheet);
			systemConfigureService.addCountryMEessage(objList);
		}
		else if (_name.equals("   ")){
			objList = readPositionExcel(sheet);
			systemConfigureService.addPositionMessage(objList);
		}
		else if(_name.equals("  ")){
			objList = readVillageExcel(sheet);
			systemConfigureService.addVillageMessage(objList);
		}
		else if(_name.equals("    ")){
			objList = readIMEIExcel(sheet);
			systemConfigureService.addIMEIMessage(objList);
		}
	}
	
/**
	 * 1       excel  
	 * @param sheet
	 * @return
	 */
	public List<Country> readCountryExcel(Sheet sheet){
		List<Country> countryList = new ArrayList<Country>();
		 int rowNum = sheet.getPhysicalNumberOfRows();  //       
		 Country country = null;
		 for (int i =1; i<rowNum; i++){
			 country = new Country();
			 Row row = sheet.getRow(i);   //   i   
			 Cell c = null;
			 if (null != row){
				 c = row.getCell(0);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 country.setCountry(c.getStringCellValue());
					 }else{
						 country.setCountry(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(1);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 country.setProvince(c.getStringCellValue());
					 }else {
						 country.setProvince(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(2);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 country.setZone(c.getStringCellValue());
					 }else {
						 country.setZone(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(3);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 country.setCode(c.getStringCellValue());
					 }else {
						 country.setCode(c.getStringCellValue());
					 }
				 }
			 }
			 countryList.add(country);
			 logger.info("print out read Excel row" + i + "Country: " + country);
		 }
		return countryList;
	}
	
	/**
	 * 2.     excel  
	 * @param sheet
	 * @return
	 */
	public List<Position> readPositionExcel(Sheet sheet){
		List<Position> positionList = new ArrayList<Position>();
		 int rowNum = sheet.getPhysicalNumberOfRows();  //       
		 Position position = null;
		 for (int i =1; i<rowNum; i++){
			 position = new Position();
			 Row row = sheet.getRow(i);   //   i   
			 Cell c = null;
			 if (null != row){
				 c = row.getCell(0);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 position.setArea(c.getStringCellValue());
					 }else {
						 position.setArea(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(1);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 position.setPosition_code(c.getStringCellValue());
					 }else {
						 position.setPosition_code(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(2);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC) {
						 c.setCellType(c.CELL_TYPE_STRING);
						 position.setPosition_name(c.getStringCellValue());
					 }else {
						 position.setPosition_name(c.getStringCellValue());
					 }
					 
				 }
			 }
			 positionList.add(position);
			 logger.info("print out read Excel row" + i + "position: " + position);
		 }
		return positionList;
	}
	
	/**
	 * 3.    excel  
	 * @param sheet
	 * @return
	 */
	public List<Village> readVillageExcel(Sheet sheet){
		StringBuffer sss=null;
		List<Village> villageList = new ArrayList<Village>();
		int rowNum = sheet.getPhysicalNumberOfRows();  //       
		   for(int i = 1; i<rowNum; i++){            
			   Row row = sheet.getRow(i);  //   i            
			   int cols = row.getLastCellNum();  //             
			   String[] str = new String[cols];   //                
			   for (int j = 0; j < cols; j++) {               
				   Object col = row.getCell((short)j);   
				   if (null != col){
					   str[j] = col.toString();          
				   }else{
					   str[j] = "";
				   }
				 	  
			   }  
			   Village v = new Village(str); 
			   logger.info("print out read String[] str" +  "str: " + Arrays.toString(str));
			   villageList.add(v);
		   }
		return villageList;
	}
	
	/**
	 * 4.      excel  
	 * @param sheet
	 * @return
	 */
	public List<IMEI> readIMEIExcel(Sheet sheet){
		List<IMEI> IMEIList = new ArrayList<IMEI>();
		 int rowNum = sheet.getPhysicalNumberOfRows();  //       
		 IMEI _imei = null;
		 for (int i =1; i<rowNum; i++){
			 _imei = new IMEI();
			 Row row = sheet.getRow(i);   //   i   
			 Cell c = null;
			 if (null != row){
				 c = row.getCell(0);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC){
						 c.setCellType(c.CELL_TYPE_STRING);
						 _imei.setIMEI(c.getStringCellValue());
					 }else{
						 _imei.setIMEI(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(1);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC){
						 c.setCellType(c.CELL_TYPE_STRING);
						 _imei.setImei_version(c.getStringCellValue());
					 }else{
						 _imei.setImei_version(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(2);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC){
						 c.setCellType(c.CELL_TYPE_STRING);
						 _imei.setImei_name(c.getStringCellValue());
					 }else{
						 _imei.setImei_name(c.getStringCellValue());
					 }
				 }
				 c = row.getCell(3);
				 if (null != c){
					 if (c.getCellType() == c.CELL_TYPE_NUMERIC){
						 c.setCellType(c.CELL_TYPE_STRING);
						 _imei.setImei_factory_name(c.getStringCellValue());
					 }else{
						 _imei.setImei_factory_name(c.getStringCellValue());
					 }
					 
				 }
			 }
			 IMEIList.add(_imei);
			 logger.info("print out read Excel row" + i + "_imei: " + _imei);
		 }
		return IMEIList;
	}
}

서비스dao 코드:
public void addCountryMEessage(List<Country> list);
	public void addIMEIMessage(List<IMEI> list);
	public void addPositionMessage(List<Position> list);
	public void addVillageMessage(List<Village> list);

서비스daoimpl 코드:
@Override
	public void addCountryMEessage(List<Country> list) {
		countryDao.addCountryMessage(list);
		
	}

	@Override
	public void addIMEIMessage(List<IMEI> list) {
		
		imeiDao.addIMEIMessage(list);
		
	}

	@Override
	public void addPositionMessage(List<Position> list) {
		positionDao.addPositionMessage(list);
		
	}

	@Override
	public void addVillageMessage(List<Village> list) {
		villageDao.addVillageMessage(list);
		
	}

xml의 sql 코드는 다음과 같습니다.
<!--     imei      -->
	<insert id="addIMEIMessage" parameterType="java.util.List">
		insert into imei 
		(IMEI, imei_version, imei_name, imei_factory_name)
		values
		<foreach collection="list" item="item" index="index" separator="," >
			(#{item.IMEI}, #{item.imei_version}, #{item.imei_name}, #{item.imei_factory_name})
		</foreach>
	</insert>

좋은 웹페이지 즐겨찾기