POI 寫的excel導入通用方法(附帶ajax上傳excel文件)

1.jsp使用jquery的ajaxfileupload插件

function importExcel(){
		if(CheckForTestFile()){
			var nwOfficeId = jQuery('#nwOfficeId')[0].value;
			$.ajaxFileUpload({
                url:'${pageContext.request.contextPath}/juasum.do?method=importExcel',             //需要鏈接到服務器地址
                secureuri:false,
                fileElementId:'fileUpload',                   //文件選擇框的id屬性
                dataType: 'text',                             //服務器返回的格式,可以是json
                data:{nwOfficeId:nwOfficeId},
                success: function (data, status) {   
                	 $('#result').html(data).attr("class",'error');
                },
                error: function (data, status, e){
               		 $('#result').html("上傳失敗!").attr("class",'error');
                }
              }
            );

		}
	}

只有部分代碼 詳細的請baidu jquery ajaxfileupload

2.action  struts1的做法

response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		FormFile[] f = (FormFile[])dynaMap.get("fileUpload");
		try {
			POIFSFileSystem in = new POIFSFileSystem(f[0].getInputStream());
			//有效數據總共9列
			Map<Integer, Map<Integer, List<String>>> map = ExcelMap.getExcel(in, 9);
			//導入數據從第3行開始
			String res = ssoUserService.importExcel(map.get(0),3,Integer.parseInt(dynaMap.get("nwOfficeId")+""));
			if("success".equals(res)){
				out.print("導入成功!");
			}else{
				out.print(res);
			}
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;

3.service

	public String importExcel(Map<Integer, List<String>> map, int i, int nwOfficeId) {
		String res = "";
		Map<String, Integer> map1 = new HashMap<String, Integer>();
		for (Entry<Integer, List<String>> ent : map.entrySet()) {
			String login_name = ent.getValue().get(0);
			if(map1.containsKey(login_name)){
				res = "第"+map1.get(login_name)+"行第1列與第"+(ent.getKey()+1)+"行第1列重複";
				return res;
			}else{
				map1.put(login_name, ent.getKey()+1);
			}
		}
		List<SSOUser> ssoUserlist = new ArrayList<SSOUser>();
		SSOUser ssoUser = null;
		List<String> list = null;
		for (Entry<Integer, List<String>> ent : map.entrySet()) {
			if(ent.getKey()>=i-1){
				ssoUser = new SSOUser();
				list = ent.getValue();
				String username = list.get(0);      //用戶名
				String nickname = list.get(1);      //暱稱
				String email = list.get(2);         //郵箱
				String sex = list.get(3);           //性別
				String regDate = list.get(4);       //註冊時間
				String phone = list.get(5);         //電話
				String age = list.get(6);           //年齡
				String address = list.get(7);       //地址
				String postcode = list.get(8);      //郵編
				if("".equals(username)){
					res = "第"+(ent.getKey()+1)+"行,第1列格式錯誤";
					return res;
				}else{
					username = nwOfficeId+"-"+username;
					int count = ssoUserDao.countSSOUserByLoginName(username);
					if (count > 0) {
						res = "第"+(ent.getKey()+1)+"行,第1列用戶名重複";
						return res;
					} else {
						ssoUser.setLoginName(username);
					}
				}
				if("".equals(nickname)){
					res = "第"+(ent.getKey()+1)+"行,第2列格式錯誤";
					return res;
				}else{
					ssoUser.setNickname(nickname);
				}
				//判斷郵箱格式
				if(!email.matches("^([\\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.[a-zA-Z0-9_-]+)+{1}quot;)){
					res = "第"+(ent.getKey()+1)+"行,第3列格式錯誤";
					return res;
				}else{
					ssoUser.setEmail(email);
				}
				//判斷性別
				if("男".equals(sex)){
					ssoUser.setSex(0);
				}else if("女".equals(sex)){
					ssoUser.setSex(1);
				}else{
					res = "第"+(ent.getKey()+1)+"行,第4列格式錯誤";
					return res;
				}
				//判斷註冊時間
				if("".equals(regDate)){
					res = "第"+(ent.getKey()+1)+"行,第5列格式錯誤";
					return res;
				}else{
					if(!regDate.matches("^\\w{3}\\s\\w{3}\\s\\d{2}\\s(\\d{2}\\:){2}\\d{2}\\sCST\\s\\d{4}{1}quot;)){
						res = "第"+(ent.getKey()+1)+"行,第5列格式錯誤";
						return res;
					}else{
						SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US); 
						try {
							ssoUser.setRegDate(sdf.parse(regDate));
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}
				Map<String, String> metadata = new HashMap<String,String>();
				//判斷電話格式
				String phone_res = getFormat(phone,"^([0-9]{3,4}\\-)?[0-9]{7,8}$|^[0-9]{11}{1}quot;);
				if("error".equals(phone_res)){
					res = "第"+(ent.getKey()+1)+"行,第6列格式錯誤";
					return res;
				}else{
					metadata.put("phone", phone_res);
				}
				//判斷年齡格式
				String age_res = getFormat(age,"^\\d{1,3}{1}quot;);
				if("error".equals(age_res)){
					res = "第"+(ent.getKey()+1)+"行,第7列格式錯誤";
					return res;
				}else{
					metadata.put("age", age_res);
				}
				metadata.put("address", address);
				//判斷郵編格式
				String postcode_res = getFormat(postcode,"^[1-9]\\d{5}{1}quot;);
				if("error".equals(postcode_res)){
					res = "第"+(ent.getKey()+1)+"行,第9列格式錯誤";
					return res;
				}else{
					metadata.put("yb", postcode_res);
				}
				ssoUser.setMetadata(metadata);
				ssoUser.setNwOfficeId(nwOfficeId);
				ssoUserlist.add(ssoUser);
			}
		}
		int m = ssoUserDao.save(ssoUserlist);
		System.out.println(m);
		return "success";
	}


4.將上傳的excel轉換成map(公用部分,適用於所有模板)

/***
	 * 
	 * @param in   POIFSFileSystem
	 * @param max  所導入excel的列數
	 * @return map
	 * @throws IOException
	 */
	public static Map<Integer, Map<Integer, List<String>>> getExcel(POIFSFileSystem in,int max)
			throws IOException {
		Map<Integer, Map<Integer, List<String>>> map = new HashMap<Integer, Map<Integer, List<String>>>();// 總map
		Map<Integer, List<String>> sheetMap = null;// 每個sheet的map
		List<String> list = null;// 每行一個list
		HSSFWorkbook workBook = null;
		try {
			workBook = new HSSFWorkbook(in);
		} catch (final Exception e) {
			throw new IOException("讀取上傳文件失敗");
		}
		/**
		 * 獲得Excel中工作表個數
		 */
		// sheet.autoSizeColumn(( short ) 0 );//導出自動適應寬度
		int sheetSize = workBook.getNumberOfSheets();
//		System.out.println("工作表個數 :" + sheetSize);
		for (int i = 0; i < sheetSize; i++) {
			sheetMap = new HashMap<Integer, List<String>>();
//			System.out.println("工作表名稱:" + workBook.getSheetName(i));
			HSSFSheet sheet = workBook.getSheetAt(i);
			int rows = sheet.getPhysicalNumberOfRows(); // 獲得行數
			if (rows > 0) {
				for (int j = 0; j < rows; j++) { // 行循環
					list = new ArrayList<String>();
					HSSFRow row = sheet.getRow(j);
					if (row != null) {
						int cells = row.getLastCellNum();// 獲得列數
						if(cells<max){
							cells = max;
						}
						for (short k = 0; k < cells; k++) { // 列循環
							HSSFCell cell = row.getCell(k);
							String value = "";
							if(cell != null){
								switch (cell.getCellType()) {
								case HSSFCell.CELL_TYPE_NUMERIC: // 數值型
									if (HSSFDateUtil.isCellDateFormatted(cell)) {
										// 如果是date類型則 ,獲取該cell的date值
										value = HSSFDateUtil.getJavaDate(
												cell.getNumericCellValue())
												.toString();
									} else {// 純數字
										value = String.valueOf(cell
												.getNumericCellValue());
									}
									if(value.matches("^((\\d+\\.?\\d+)[Ee]{1}(\\d+)){1}quot;)){
										DecimalFormat df = new DecimalFormat("#.##");
										value = df.format(Double.parseDouble(value));
									}
									break;
								case HSSFCell.CELL_TYPE_STRING: // 字符串型
									value = cell.getRichStringCellValue()
											.toString().trim();
									break;
								case HSSFCell.CELL_TYPE_FORMULA:// 公式型
									// 讀公式計算值
									value = String.valueOf(cell
											.getNumericCellValue());
									if (value.equals("NaN")) {// 如果獲取的數據值爲非法值,則轉換爲獲取字符串
										value = cell.getRichStringCellValue()
												.toString();
									}
									break;
								case HSSFCell.CELL_TYPE_BOOLEAN:// 布爾
									value = "" + cell.getBooleanCellValue();
									break;
								/* 此行表示該單元格值爲空 */
								case HSSFCell.CELL_TYPE_BLANK: // 空值
									value = "";
									break;
								case HSSFCell.CELL_TYPE_ERROR: // 故障
									value = "";
									break;
								default:
									value = cell.getRichStringCellValue()
											.toString().trim();
								}
							}
							list.add(value);
						}
						if(!isAllNull(list)){
							sheetMap.put(j, list);
						}
					}
				}
			}
			map.put(i, sheetMap);
		}
		return map;
	}
	/**
	 * 如果list裏面的值全爲空 則範圍true 反之則爲false
	 * @param l list
	 * @return
	 */
	private static boolean isAllNull(List<String> l){
		int i=0;
		for(String s : l){
			if(!"".equals(s)){
				i++;
			}
		}
		if(i>0){
			return false;
		}
		return true;
	}
	
	public static void main(String[] args) {
		String filePath = "d:/template.xls";
		try {
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath)); 
			Map<Integer, Map<Integer, List<String>>> map = getExcel(fs,9);
			for(Entry<Integer, List<String>> ent : map.get(0).entrySet()){
				System.out.println(ent);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}


本版本採用poi-3.6-20091214.jar jar包可以在我的csdn資源列表裏面下載

excel2003 2007均適用

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