导入Excel并保存到数据库

阅读更多

Excel模版(注意每行是三行合并的):

 

先将Excel文件上传到服务器,然后展示到页面上,再点击“保存到数据库”实现插入数据库

1、先导入

上传控件为uploadxls.js

上传调用方法为purcharseUpload.js中的importFile()方法

上传请求为purchaseUpload.js中initUpload()方法中的serverUrl

前台页面文本框saveFile展示上传后的文件路径

 

前台:


导入订单

 

上传方法(文件purchseUpload.js):

var globalUpload = "";

function importFile(){
	//pwidth = '150';
	//pheight = '150';
	$("#btnSave").show();
	$("#dialog-modal").dialog("open");
	initUpload();
    return false;
}


//上传组件的初始化操作
function initUpload() {
	if($('#popUploadFlash').length==0){
         $("#shopDesignLogo").after("
"); } var pwidth,pheight; //pwidth = '150'; //pheight = '150'; var uploadParameter = { //以下为必须要的 'serverUrl': '/fileUpload', //服务器端脚本的位置 'flashUrl': '/js/uploadnew/swfupload.swf', //上传flash的位置 'uploadButtonUrl': '/js/uploadnew/XPButtonUploadText_61x22.png', //flash上传按钮图片的位置 'uploadContainer': 'popUploadFlash', //在页面中用来放上传flash的容器 'uploadFun': 'uploadBack', //上传成功后执行的函数 'appNum': 'selleck', //App编号 'imageResizeList': '1000X1000', //截图尺寸 //'picWidth' : pwidth, //'picHeigth' : pheight, 'uploadFirst': true, //是否先上传,如果是的话,上传框将附带上传按钮,否则不带 //以下为非必须选项 'uploadFrameLength': '200' //整个上传框的长度 }; loadUploadFlash(uploadParameter); $("#popUploadFlash").attr("style","float:left;"); } //上传后的回调函 function uploadBack(serverData) { if(serverData.content == "ok"){ var saveFile = serverData.path; $("#saveFile").attr("value" , saveFile); //上传成功后将数据显示在前台 window.location.href = "/purchase/importOrder.do?saveFile=" + saveFile; } var src=serverData.path; if(serverData.ret == 'false'){ alert(serverData.content); }else{ exportData(src); $("#dialog-modal").dialog("close"); } initUpload(globalUpload); //重新生成一个上传组件 }

 

进入前台请求:


	/WEB-INF/ftl/purchase/importOrderList.ftl

				


	/WEB-INF/ftl/purchase/importOrderList.ftl

 

前台页面importOrderList.ftl:(默认页面和上传后展示页面为同一个)

        

导入订单
<#if cdosOrder?exists> <#list cdosOrder as item> <#else>
序号 采购单号 运费 采购日期 预计到货时间 下单时间 商品编号 商品名称 订购数量 商品单价 供应商 供应商CODE 手机号码 详细地址 订单备注 采购员 采购员电话
${item_index + 1} <@getStringValue cdo=item col='0'/> <@getStringValue cdo=item col='1'/> <@getStringValue cdo=item col='2'/> <@getStringValue cdo=item col='3'/> <@getStringValue cdo=item col='4'/> <@getStringValue cdo=item col='5'/> <@getStringValue cdo=item col='6'/> <@getStringValue cdo=item col='7'/> <@getStringValue cdo=item col='8'/> <@getStringValue cdo=item col='9'/> <@getStringValue cdo=item col='10'/> <@getStringValue cdo=item col='11'/> <@getStringValue cdo=item col='12'/> <@getStringValue cdo=item col='13'/> <@getStringValue cdo=item col='14'/> <@getStringValue cdo=item col='15'/> <@getStringValue cdo=item col='16'/> <@getStringValue cdo=item col='17'/> <@getStringValue cdo=item col='18'/>

   

 

后台上传(将数据从Excel中提出然后汇总为cdosOrder数据):

public String toImportOrder(){
		cdosOrder = null;
		return SUCCESS;
	}
	
	/**
	 * 显示上传的订单
	 * @return
	 * @throws Exception
	 */
	public String importOrder() throws Exception{
		cdosOrder = null;      	
		String filePath = request.getParameter("saveFile");
		request.setAttribute("filePath", filePath);
		InputStream is = new FileInputStream(request.getRealPath(filePath));
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		
		// 循环工作表Sheet
		HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
		int rows = hssfSheet.getLastRowNum();
		cdosOrder = new CDO[rows];
		int sheetmergerCount = hssfSheet.getNumMergedRegions();
		
		//org.apache.poi.ss.util.CellRangeAddress
		List list = new ArrayList();
		for (int i = 0; i < sheetmergerCount; i++) {
			// 获得合并单元格加入list中			
			CellRangeAddress ca = hssfSheet.getMergedRegion(i);
			list.add(ca);
		}
		
		// 循环行Row
		for (int rowNum = 1; rowNum <= rows; rowNum++) {
			HSSFRow hssfRow = hssfSheet.getRow(rowNum);
			if(hssfRow != null){
				CDO cdoItem = new CDO();
				//循环列
				for (int cellNum = 0; cellNum <= 18; cellNum++) {
					@SuppressWarnings("unused")
					String value = "";
					@SuppressWarnings("unused")
					HSSFCell hssfCell = hssfRow.getCell(cellNum);
					//循环合并的单元格
					for(int i = 0 ; i < sheetmergerCount ; i++)
					{
						CellRangeAddress cr = list.get(i);
						int c = cr.getLastRow() - cr.getFirstRow();
						
						for(int m = c ; m >= 0 ; m--){
							if(rowNum - m == cr.getFirstRow()){
								hssfRow = hssfSheet.getRow(rowNum - m);
							}
							else if(cellNum == 0 || cellNum == 4 || cellNum == 5 || cellNum == 6|| cellNum == 7 || cellNum == 8){
								hssfRow = hssfSheet.getRow(rowNum);
							}
							else{
								hssfRow = hssfSheet.getRow(rowNum);
							}
						}
						
						hssfCell = hssfRow.getCell(cellNum);
					}
					
					if (hssfCell != null) {
						value = getValue(hssfCell);
						
						/*if(cellNum == 1){
							value = e2Conventional(value);
							
							int s = value.indexOf(".");
							value = s == -1 ? value : value.substring(0,s);
						}
						//设定显示格式
						if(!value.trim().isEmpty() && (cellNum == 1 || cellNum == 4 || cellNum == 10)){
							value = e2Conventional(value);
						}
						else if(!value.trim().isEmpty() && (cellNum == 2 || cellNum == 8)){
							value = df.format(Double.parseDouble(value));
						}
						else if(!value.trim().isEmpty() && (cellNum == 7 || cellNum == 15)){
							Float fv = Float.parseFloat(value);
							Integer iv = fv.intValue();
							value = iv.toString();
						}*/
					}
					cdoItem.setStringValue(String.valueOf(cellNum), value.trim());
				}
				cdosOrder[rowNum-1] = cdoItem;
			}
			else{
				cdosOrder = null;
				break;
			}
		}
		
		
		return SUCCESS;
	}

 

 

保存到数据库JS:

function save2db(){
	//判断单价为0,不是售后的订单
	var length = $('.importTr').length;
	for(var i=0;i 
  

 

保存到数据库后台(注意合并判断和金额计算):

/**
	 * 保存导入的订单到数据库
	 * @throws Exception 
	 */
	public void save2db() throws Exception{
		
		cdosOrder = null;
		//查询
		String filePath =  request.getParameter("filename");
		request.setAttribute("filePath", filePath);
		InputStream is = new FileInputStream(request.getRealPath(filePath));
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		
		// 循环工作表Sheet
		HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
		int rows = hssfSheet.getLastRowNum();
		cdosOrder = new CDO[rows];
		int sheetmergerCount = hssfSheet.getNumMergedRegions();
		
		List list = new ArrayList();
		for (int i = 0; i < sheetmergerCount; i++) {
			// 获得合并单元格加入list中			
			CellRangeAddress ca = hssfSheet.getMergedRegion(i);
			list.add(ca);
		}
		
		// 循环行Row
		for (int rowNum = 1; rowNum <= rows; rowNum++) {
			HSSFRow hssfRow = hssfSheet.getRow(rowNum);
			if(hssfRow != null){
				String nShopId = "";
				CDO cdoItem = new CDO();
				//循环列
				for (int cellNum = 0; cellNum <= 18; cellNum++) {
					String value = "";
					HSSFCell hssfCell = hssfRow.getCell(cellNum);
					//循环合并的单元格
					for(int i = 0 ; i < sheetmergerCount ; i++)
					{
						CellRangeAddress cr = list.get(i);
						int c = cr.getLastRow() - cr.getFirstRow();
						
						for(int m = c ; m >= 0 ; m--){
							if(rowNum - m == cr.getFirstRow()){
								hssfRow = hssfSheet.getRow(rowNum - m);
							}
							else if(cellNum == 5 || cellNum == 6 || cellNum == 7 || cellNum == 8){
								hssfRow = hssfSheet.getRow(rowNum);
							}
						}
						
						hssfCell = hssfRow.getCell(cellNum);
					}
					
					if (hssfCell != null && cellNum < 15) {
						value = getValue(hssfCell).trim();
						
						if(cellNum == 1){
							value = e2Conventional(value);
							
							int s = value.indexOf(".");
							value = s == -1 ? value : value.substring(0,s);
						}
						if((cellNum == 7 || cellNum == 8) && Float.parseFloat(value) < 0.00f){
							String str = "第" + rowNum + "行,第" + cellNum + "列不能为负数";
							ajaxForAction(ServletActionContext.getResponse(),str);
							return;
						}
						
						if(value.equals("")){
							String str = "第" + rowNum + "行,第" + cellNum + "列不能为空";
							ajaxForAction(ServletActionContext.getResponse(),str);
							return;
						}
						
						//设定显示格式
						if(!value.trim().isEmpty() && (cellNum == 0 || cellNum == 5 || cellNum == 10)){
							value = e2Conventional(value);
						}
						else if(!value.trim().isEmpty() && (cellNum == 1 || cellNum == 8)){
							value = df.format(Double.parseDouble(value));
						}
						else if(!value.trim().isEmpty() && cellNum == 7 ){
							Float fv = Float.parseFloat(value);
							Integer iv = fv.intValue();
							value = iv.toString();
						}
					}
					else if(cellNum < 15){
						String str = "第" + rowNum + "行,第" + cellNum + "列不能为空";
						ajaxForAction(ServletActionContext.getResponse(),str);
						return;
					}
					else if (hssfCell != null) {
						value = getValue(hssfCell);
					}
										
					// 导入模板存在商品总价字段,但是与商品单价*数量+运费 不相等。因此导入时去掉商品总价列,由后台计算值
					// 去除商品总价那列的导入,后面逻辑不变
					if(cellNum >= 2){
						int cell = cellNum + 1;
						cdoItem.setStringValue(String.valueOf(cell), value.trim());
					}else{
						cdoItem.setStringValue(String.valueOf(cellNum), value.trim());
					}
				}
				// 运费
				String val2 = cdoItem.getStringValue("1");
				// 商品数量
				int val7 = cdoItem.getIntegerValue("8");
				// 商品单价
				String val8 = cdoItem.getStringValue("9");
				
				Float fval8 = Float.parseFloat(val8);
				Float fval2 = Float.parseFloat(val2);
				
				// 当前行与上一行的订单相同,只算一次运费
				if(rowNum != 1 && cdoItem.getStringValue("0").equals(cdosOrder[rowNum-2].getStringValue("0"))){
					Float fval = fval8 * val7;
					cdoItem.setStringValue("2", fval.toString());
					cdosOrder[rowNum-1] = cdoItem;
				}else{
					Float fval = fval8 * val7 + fval2;
					cdoItem.setStringValue("2", fval.toString());
					cdosOrder[rowNum-1] = cdoItem;
				}
			}
			else{
				cdosOrder = null;
				ajaxForAction(ServletActionContext.getResponse(), "Excel文档的第" + rowNum + "行是空行,请检查。");
				return;
			}
		}
		
		for(int i = 0 ; i < cdosOrder.length ; i++){
			int k = i + 1;
			
			String valueDate = cdosOrder[i].getStringValue("5");
			if(!checkDate(valueDate)){
				String str = "第" + k + "行:下单时间格式应为yyyy-mm-dd hh:mm:ss";
				ajaxForAction(ServletActionContext.getResponse(), str);
				return;
			}
			
			// 上传订单限制只能上传昨天和今天的订单
			Calendar cal = Calendar.getInstance();
			// 今天年月日
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
			String dateNowStr = sdf1.format(date.getTime());
			
			// 传过来的日期 年月日
			Date compare1 = sdf.parse(valueDate);
			// 传过来的日期 年月日时分秒
			Date compare11 = sdf1.parse(valueDate);
			// 今天 年月日时分秒
			Date compare2 = sdf.parse(dateNowStr);
			
			cal.add(Calendar.DATE,   -1);
			String yesterday = sdf.format(cal.getTime());
			// 昨天 年月日
			Date compare3 = sdf.parse(yesterday);
			
			// 今天的单只能上传当前时间之前的
			/*if(DateUtils.compare(compare1, compare2) == 0 && (DateUtils.compare(compare11, date) != -1)){
				String str = "第" + k + "行:只能上传昨天和当前时间之前的订单";
				ajaxForAction(ServletActionContext.getResponse(), str);
				return;
			}*/
			 // 今天之后的不可上传
			 if(DateUtils.compare(compare11, date) == 1){
				String str = "第" + k + "行:只能上传昨天和当前时间之前的订单";
				ajaxForAction(ServletActionContext.getResponse(), str);
				return;
			}
			// 可以上传昨天的订单
			/*else if(DateUtils.compare(compare1, compare2) != 0 && DateUtils.compare(compare1, compare3) != 0){
				String str = "第" + k + "行:只能上传昨天和当前时间之前的订单";
				ajaxForAction(ServletActionContext.getResponse(), str);
				return;
			}*/
		    
		}

		if(cdosOrder != null){
			for(int m = 0 ; m < cdosOrder.length ; m++){
				String strValueOrderCode = cdosOrder[m].getStringValue("0");				
				cdosOrder[m].setStringValue("0" , "P"+strValueOrderCode);
			}
		}
      //订单号是否存在
		for(int i = 0 ; i < cdosOrder.length ; i++){
			String strCode = cdosOrder[i].getStringValue("0");
			if(checkOrderCode(strCode)){
				ajaxForAction(ServletActionContext.getResponse(),"订单号" + strCode + "已存在。");
				return;
			}
		}
		
		//保存
		cdoRequest.setStringValue(ITransService.TRANSNAME_KEY,"getProductList");
		cdoRequest.setStringValue(ITransService.SERVICENAME_KEY,"purchaseService");
      	Return ret = getServiceBus().handleTrans(cdoRequest, cdoResponse);
      	CDO[] cdosProduct = null;
      	CDO[] cdos = null;
      	
      	if(ret.getCode() == 0){
      		cdosProduct = cdoResponse.getCDOArrayValue("cdosProduct");
      		
      		//验证商品编号是否存在
      		for(int i = 0 ; i < cdosOrder.length ; i++){
      			boolean flag = false;
      			for(CDO cdo : cdosProduct){
      				if(!cdosOrder[i].getStringValue("6").equals(cdo.getStringValue("strProductCode"))){
      					flag = false;
      				}
      				else{
      					flag = true;
      					break;
      				}
      			}

  				if(!flag){
  	      			int k = i + 1;
  					String str = "第" + k + "行:商品编号不存在";
  					ajaxForAction(ServletActionContext.getResponse(), str);
  					return;
  				}
      		}

      		//合并相同订单号
      		HashMap map = new HashMap();
      		int idx = 0;
      		for(int i = 0 ; i < cdosOrder.length ; i++){
      			
      			CDO cdo = cdosOrder[i];
      			if(i != 0 && cdo.getStringValue("0").equals(cdosOrder[i - 1].getStringValue("0"))){
      				String totleMoney1 = cdo.getStringValue("2");
      				String totleMoney2 = cdosOrder[i - 1].getStringValue("2");
      				Float fv1 = Float.parseFloat(totleMoney1);
      				Float fv2 = Float.parseFloat(totleMoney2);
      				Float fv3 = fv1 + fv2;
      				cdo.setStringValue("2", fv3.toString());
      				map.put(idx-1, cdo);
      			}
      			else{
	      			map.put(idx, cdo);
	      			idx ++;
      			}
      		}
      		
      		HashMap hashmapPro = new HashMap();
      		for(int m = 0 ; m < cdosOrder.length ; m++){
      			String strPC = cdosOrder[m].getStringValue("0");
      			String strProCode = cdosOrder[m].getStringValue("6");
      			String strGoodsTitle = cdosOrder[m].getStringValue("7");
      			String strnPrice = cdosOrder[m].getStringValue("9");
      			String strnCount = cdosOrder[m].getStringValue("8");
      			String strCustomerCode = cdosOrder[m].getStringValue("11");
      			String strlGoodsId = "";
      			String strLogoURL = "";
      			String strBasicUnit = "";
      			String nType = "0";
      			String cusId = "";
      			String cusCode = "";
      			
      			for(CDO product : cdosProduct){
	      			if(cdosOrder[m].getStringValue("6").trim().equals(product.getStringValue("strProductCode").trim())){
	      				strlGoodsId = product.getStringValue("nProductId").trim();
	      				//strLogoURL = product.getStringValue("strLogoURL").trim();
	      				strBasicUnit = product.getStringValue("strBasicUnit").trim();
	      			}
	      			
	      			String nCustomerId = product.getStringValue("nCustomerId");
	      			String customerCode = product.getStringValue("strCustomerCode");
	      			
	      			if(customerCode.trim().equals(strCustomerCode.trim())){
	      				cusId = nCustomerId;
	      				cusCode = strCustomerCode;
	      			}
      			}
				
				StringBuffer strbf = new StringBuffer();
				strbf.append(",{");
				strbf.append("\"lGoodsId\":\"");
				strbf.append(strlGoodsId);
				strbf.append("\",\"strGoodsTitle\":\"");
				strbf.append(strGoodsTitle);
				strbf.append("\",\"nPrice\":\"");
				strbf.append(strnPrice);
				strbf.append("\",\"nCount\":\"");
				strbf.append(strnCount);
				strbf.append("\",\"strProCode\":\"");
				strbf.append(strProCode);
				strbf.append("\",\"nType\":\"");
				strbf.append(nType);
				strbf.append("\",\"strLogoURL\":\"");
				//strbf.append(strLogoURL);
				strbf.append("\"");
				
				strbf.append("\",\"nCustomerId\":\"");
				strbf.append(cusId);
				strbf.append("\",\"strCustomerCode\":\"");
				strbf.append(cusCode);
				strbf.append("\",\"strBasicUnit\":\"");
				strbf.append(strBasicUnit);
				strbf.append("\"");
				
				strbf.append("}");
				strbf.append(",");
      			
      			hashmapPro.put(strPC, (hashmapPro.get(strPC) != null ? hashmapPro.get(strPC) : "") + strbf.toString().substring(0, strbf.toString().length() - 1));
      		}
      		cdos = new CDO[map.size()];
      		for(int i = 0 ; i < map.size() ; i++){
      			CDO cdoOrder = (CDO) map.get(i);
      			cdoOrder.setIntegerValue("nImportUserId", getLoginID());
      			//订单号
      			String strOC = cdoOrder.getStringValue("0");
      			for(int j = 0 ; j < hashmapPro.size() ; j++){
      				String strHMOC = (String) hashmapPro.get(strOC);
      				cdoOrder.setStringValue("31", "[" + strHMOC.substring(1) + "]");
      				
      				CDO[] cdosPro = strJson2CDOAry(strHMOC.substring(1));
      				cdoOrder.setCDOArrayValue("cdosOP", cdosPro);
      				int nGoodsAmount = 0;
      				for(int m = 0 ; m < cdosPro.length ; m++){
      					nGoodsAmount += cdosPro[m].getIntegerValue("nQuantity");
      				}
      				cdoOrder.setIntegerValue("nGoodsAmount", nGoodsAmount);
      			}
      			
      			/*
      			if(cdoOrder.getStringValue("18").trim().equals("普通发票")){
	      			cdoOrder.setStringValue("strNeedreceiptType", "普通发票");
	      			cdoOrder.setStringValue("bNeedreceipt", "0");
      			}
      			else{
      				cdoOrder.setStringValue("strNeedreceiptType", "");
      				cdoOrder.setStringValue("bNeedreceipt", "1");
      			}
      			
      			if(cdoOrder.getStringValue("21").trim().equals("货到付款")){
	      			cdoOrder.setStringValue("21", "BJJD");
      			}
      			else{
      				cdoOrder.setStringValue("21", "");
      			}
      			
      			if(cdoOrder.getStringValue("22").trim().equals("3C店")){
      				cdoOrder.setStringValue("22", "1");
      			}
      			else if(cdoOrder.getStringValue("22").trim().equals("数码店")){
      				cdoOrder.setStringValue("22", "2");
      			}
      			else{
      				cdoOrder.setStringValue("22", "0");
      			}*/
      			
      			cdos[i] = cdoOrder;
      		}
      	}

		cdoRequest.setCDOArrayValue("cdosOrder", cdos);
		cdoRequest.setStringValue(ITransService.TRANSNAME_KEY,"saveOrderList");
      	ret = getServiceBus().handleTrans(cdoRequest, cdoResponse);
      	if(ret.getCode() == 0){
      		ajaxForAction(ServletActionContext.getResponse(),"0");
      	}
      	else{
      		ajaxForAction(ServletActionContext.getResponse(),"-5");
      	}
	}
	
	
	
	@SuppressWarnings("static-access")
	private static String getValue(HSSFCell hssfCell) {
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			return String.valueOf(hssfCell.getNumericCellValue());
		} else {
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}
	
	/**
	 * 科学计数法转普通计数法
	 * @param value
	 * @return
	 */
	private static String e2Conventional(String value){
		BigDecimal db = null;
		try{
			if(!value.startsWith("0")){
				db = new BigDecimal(value);
				value = db.toPlainString();
			}
		}
		catch(Exception e){
			
		}
		
		return value;
	}
	
	/**
	 * 日期格式验证
	 * YYYY-MM-DD hh:mm:ss
	 * @param str
	 * @return
	 */
	private static boolean checkDate(String str){
		boolean flag = false;
		
		if(str.equals("")){
			flag = false;
		}
		else{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
			try {
				sdf.parse(str);
				flag = true;
			}
			catch (java.text.ParseException e)
			{  
				flag = false;
			} 
		}
		
		return flag;
	}

 。。

 

 

  • 导入Excel并保存到数据库_第1张图片
  • 大小: 18.3 KB
  • 导入Excel并保存到数据库_第2张图片
  • 大小: 10.2 KB
  • uploadXls控件.rar (88.9 KB)
  • 下载次数: 0
  • jar包.rar (6.9 MB)
  • 下载次数: 0
  • Excel模版.rar (9.4 KB)
  • 下载次数: 0
  • 代码.rar (3.2 KB)
  • 下载次数: 2
  • 查看图片附件

你可能感兴趣的:(导入Excel并保存到数据库)