导入excel文件将数据插入到数据库并且以列表形式展示

本文介绍了一个基于前端和Java实现的Excel导入功能,包括前端页面设计、JavaScript交互逻辑及后端处理流程。展示了如何验证文件类型、大小,以及通过读取Excel内容进行数据校验和导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、前端页面(只展示核心代码片段,即文件导入按钮)

    

<form class="form-inline" id="productSearchForm">
	    
	<div class="form-group">
	        <label for="productName">产品名称:</label> 
                <input type="text" class="form-control input-sm" name="productName" />
	</div>
		
        <button type="button" class="b-redBtn btn-i" id="searchBtn">
	    <i class="iconfont"></i>查询
	</button>
	  
	<button type="button" class="b-redBtn  btn-i" id="resetBtn">
	    <i class="iconfont"></i>重置查询
	</button>
	  
        <button type="button" class="b-redBtn  btn-i" id="addProductBtn">
	    <i class="iconfont"></i>新增产品
	</button>
	  
	<a id="downloadFile" href="<%=webpath%>/resources/js/orderCenter/productTabTemplet.xlsx">
	     <button type="button" class="b-redBtn  btn-i" id="downloadTempletBtn">
	        <i class="iconfont"></i>模板下载
	     </button>
        </a>
	  
	   <input type="file" name="files" id="files" style="display:none;" />
	  
	   <button type="button" class="b-redBtn  btn-i" id="excelImportBtn" onclick="scan()">
	      <i class="iconfont"></i>excel导入
	   </button>
	   
	  <span id="fileInput"></span>
	   
</form>
2、核心js代码片段展示

function scan() {
    var files = document.getElementById("files");
    files.setAttribute("onchange", "fileCheck(this)");
    layer.confirm('导入excel前,请先下载左侧模板、按照模板指定格式,完成填写并导入,否则会导入失败!', {
        icon: 3,
        btn: ['是', '否'] //按钮
    }, function (index, layero) {
        layer.close(index);
        files.click();
    });
}

function fileCheck(obj) {
    for (var i = 0; i < obj.files.length; i++) {
        var fileName = obj.files[i].name;
        var postfix = obj.files[i].name.match(/^(.*)(\.)(.{1,8})$/)[3].toLowerCase(); //获得上传文件的后缀名的正则表达式;
        var fileMaxSize = (obj.files[i].size / 1024 / 1024).toFixed(2);                     //前端获取待上传的文件大小
        if (!(postfix == "xlsx" || postfix == "xls")) {
            layer.confirm('文件类型不正确,请重新上传excel文件!', {
                icon: 3,
                btn: ['是', '否'] //按钮
            }, function (index, layero) {
                layer.close(index);
                //window.location.href=webpath+"/orderCenter/productManage";
            });
            $('#files').val('');
            return false;
        }
        ;

        if (fileMaxSize > 1) {
            layer.confirm('excel文件文件大小不得超过1M,请重新上传 !', {
                icon: 3,
                btn: ['是', '否'] //按钮
            }, function (index, layero) {
                layer.close(index);
            });
            $('#files').val('');
            return false;
        }
        var fileNameInput = document.getElementById("fileInput");
        fileNameInput.innerText = fileName;
        //layer.msg(content, options, end)开始导入数据

        layer.msg('开始导入excel数据,请稍等...', {
            icon: 6,
            time: 3000 //3秒关闭(如果不配置,默认是3秒)
        }, function () {
            //layer.alert('测试');
            $.ajaxFileUpload({
                url: webpath + "/orderCenter/importExcel",
                fileElementId: "files",
                type: "post",
                dataType: "text",
                data: {"flag": "开始导入"},
                success: function (data) {
                    var result = data.replace("<pre>", "").replace("</pre>", "").replace("<PRE>", "").replace("</PRE>", "").replace(/<[^>]+>/g, "");
                    var resultFlag = $.parseJSON(result);
                    receiveData(resultFlag);
                }
            });
            console.log("已经导入excel中的数据");
        });

        function receiveData(resultFlag) {
            if (resultFlag.idIsNull == "true") {
                alert('导入失败,导入的产品ID存在空值,位于表格第' + resultFlag.errorLine + '行');
            }

            if (resultFlag.idIsRepeat == "true") {
                alert('导入失败,导入的产品ID存在重复,请仔细检查!');
            }

            if (resultFlag.idCodeIsNotSame == "true") {
                alert('导入失败,导入的产品ID和产品编码不一致,位于表格第' + resultFlag.errorLine + '行');
            }

            if (resultFlag.excelAndTabRepeat == "true") {
                alert('导入失败,导入的产品编码在数据库码表中早已存在,重复的产品编码为' + resultFlag.repeatCode);
            }
            window.location.href = webpath + "/orderCenter/productManage";
            console.log("导入完成");
        }
    }
}

3、java核心代码展示

	// 导入产品的表格数据
	@ResponseBody
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Map<String,Object> importExcel(String flag, HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		String fileName = null;
		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
			Iterator<?> iter = mr.getFileMap().values().iterator();
			// 支持多文件上传,暂时是单文件的上传
			if (iter.hasNext()) {
				MultipartFile file = (MultipartFile) iter.next();
				try {
					Workbook book = null;
					try {
						book = new XSSFWorkbook(file.getInputStream());
					} catch (Exception ex) {
						book = new HSSFWorkbook(file.getInputStream());
					}
					// 获得第一个工作薄
					Sheet sheet = book.getSheetAt(0);
					Row row = null;
					Row row2 = null;
					Row row3=null;
					boolean idIsNull=false;
					int errorLine=0;
					//判断product_id是否有重复
					boolean isRepeat = false;
					//id和code是否相同idCodeIsSame
					boolean idCodeIsNotSame=false;
					// 获得总行数
					int totalRows = sheet.getLastRowNum();
					// 获得总列数
					int coloumNum = sheet.getRow(1).getPhysicalNumberOfCells();
					System.out.println("总行数totalRows==>" + totalRows);
					System.out.println("总列数coloumNum==>" + coloumNum);
					System.out.println("开始获取表格中的数据");
					// 表格数据的行数为
					int verifyNum = totalRows - 2;
					String[] procIdArr = new String[verifyNum];
					String[] procCodeArr = new String[verifyNum];
					
					for (int i = 3; i <= totalRows; i++) {
						row2 = sheet.getRow(i);						
						if(null !=row2.getCell(0)){
							System.out.println("row2.getCell(0)===>"+row2.getCell(0));
							String tem = row2.getCell(0).toString();
							System.out.println("第一列procId:从第三行开始--》" + tem);
							procIdArr[i - 3] = tem;	
						}
						if(null==row2.getCell(0)){
							idIsNull=true;
							errorLine=i+1;
							String errorLineStr=String.valueOf(errorLine);
							params.put("idIsNull", "true");
							params.put("errorLine", errorLineStr);
							System.out.println("--idIsNull---"+idIsNull+"---errorLine-->"+errorLine);
							return params;
						}						
					}
					
					Set<String> set = new HashSet<String>();
					for (String str : procIdArr) {
						set.add(str);
					}
					if (set.size() != procIdArr.length) {
						isRepeat = true;// 重复
						params.put("idIsRepeat", "true");
						return params;
					} else {
						isRepeat = false;// 不重复
					}					
					System.out.println("判断productId是否存在重复的判断结果为==>"+isRepeat);
					
					for (int i = 3; i <= totalRows; i++) {
						row3 = sheet.getRow(i);
						String tem3 = row3.getCell(1).toString();
						System.out.println("第二列:从第三行开始--》" + tem3);
						procCodeArr[i - 3] = tem3;
					}	
					for (int k = 0; k < procIdArr.length; k++) {
						if(!procCodeArr[k].equals(procIdArr[k])){
							idCodeIsNotSame=true;
							errorLine=k+4;
							String errorLineStr=String.valueOf(errorLine);
							params.put("idCodeIsNotSame", "true");
							params.put("errorLine", errorLineStr);
							return params;							
						}
					}					
					System.out.println("id和code是否相同"+idCodeIsNotSame+"是在第几行==>"+errorLine);	
					
					//校验表格id和数据库码表中的id是否有相同,有相同,则不让其导入;					
					for(int i=0;i<procCodeArr.length;i++){
						String excelAndTabRepeat=orderCenterService.validateProCodeIsExist(procCodeArr[i]);
						if(null!=excelAndTabRepeat){
							params.put("excelAndTabRepeat", "true");
							params.put("repeatCode", excelAndTabRepeat);
							return params;
						}
					}

					for (int i = 3; i <= totalRows; i++) {
						row = sheet.getRow(i);
						if (row == null) {
							continue;
						}
						for (int k = 0; k < coloumNum; k++) {
							String productField = sheet.getRow(2).getCell(k).toString().trim();
							if (!"ORD".equalsIgnoreCase(productField) && !"RST6".equalsIgnoreCase(productField) && !"RST7".equalsIgnoreCase(productField)) {
								if (row.getCell(k) == null) {
									params.put(productField, "");
									continue;
								}
								String productFieldValue = row.getCell(k).toString().trim();
								params.put(productField, productFieldValue);
							}
							if ("ORD".equalsIgnoreCase(productField)) {
								if (row.getCell(k) == null) {
									params.put(productField, "");
									continue;
								}
								String productFieldValue = row.getCell(k).toString().trim();
								// 数据库码表中,字段类型为mediumint
								params.put(productField, Integer.parseInt(productFieldValue));
							}
							if ("RST6".equalsIgnoreCase(productField) || "RST7".equalsIgnoreCase(productField)) {
								if (row.getCell(k) == null) {
									params.put(productField, "");
									continue;
								}
								String productFieldValue = row.getCell(k).toString().trim();
								// 数据库码表中,字段类型为decimal
								BigDecimal bd = new BigDecimal(productFieldValue);
								params.put(productField, bd);
							}
						}
						// 开始执行测试代码
						System.out.println("=======" + i);
						System.out.println(params);
						// 开始将表格数据导入到数据库
						orderCenterService.importExcelDatas(params);
					}
					fileName = file.getOriginalFilename();
					System.out.println("文件名为:" + fileName);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		params.put("processNormal", "true");
	  return params;
	}

4、需要导入的maven依赖包有(注意local.import.utils下的jar包是笔者手动导入本地仓库的,读者可以自行在网上下载)

  	
  		<dependency>
  		     <groupId>local.import.utils</groupId>
  		     <artifactId>poi-ooxml</artifactId>
  		     <version>3.9</version>
  		</dependency>
 
 
  		<dependency>
  		     <groupId>local.import.utils</groupId>
  		     <artifactId>poi</artifactId>
  	             <version>3.9</version>
  		</dependency>
			
  		<dependency>
  		     <groupId>org.apache.xmlbeans</groupId>
  		     <artifactId>xmlbeans</artifactId>
  		     <version>2.6.0</version>
  		</dependency>
			
  		<dependency>
  		     <groupId>org.apache.poi</groupId>
  		     <artifactId>ooxml-schemas</artifactId>
  		     <version>1.1</version>
				
  	        </dependency>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值