java-导入

本文详细介绍了一个基于Java的Excel数据导入功能实现,包括实体类注解使用、前后端交互流程、控制器处理逻辑及自定义Excel工具类。展示了如何通过注解映射实体字段与Excel列,前端如何选择并上传文件,后端如何解析并保存数据。

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

由于数据量很多,需要导入这个功能。
需要注意的几个地方
1.实体需要给每个字段填加注释:@ExcelVOAttribute(name = “公司名称”, column = “A”)

@ExcelVOAttribute(name = "公司名称", column = "A")
    private String companyName;

    @ExcelVOAttribute(name = "公司英文名称", column = "B")
    private String enCompanyName;

    @ExcelVOAttribute(name = "招展代理", column = "C")
    private String exhibitorAgent;

与Excel表格相对应
在这里插入图片描述
2.前端jsp

$('#excelPath').change(function () {
            var excelPath = $("#excelPath").val();
            if (excelPath == null || excelPath == '') {
                alert("请选择要上传的Excel文件");
                return;
            } else {
                var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();
                if (fileExtend == '.xls') {
                    $("#upload").ajaxSubmit({
                        url: "${ctx}/exhibitor/oldcustomer/importOldExhibitorExcel.action",
                        cache: false,
                        dataType: 'json',
                        success: function (ret) {
                            console.log("导入历史展商返回结果:" + ret);
                              layer.msg('导入成功');
                            page();
                            $('#upload')[0].reset()
                        },
                        error: function (ret) {
                            layer.msg(ret.msg);
                            alert("error");
                            $('#upload')[0].reset()
                        }

                    });
                } else {
                    alert("文件格式需为'.xls'格式");
                    return;
                }
            }
        });

后端Controller

//导入历史展商数据
    @RequestMapping(value = "/importOldExhibitorExcel", method = RequestMethod.POST)
    @ResponseBody
    public CommonStatus importOldExhibitorExcel(@RequestParam(value = "excelPath", required = false) MultipartFile file) {
        LOGGER.info("批量导入历史展商");
        boolean isAllow = false;
        String fileName = file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        if (index < 0) {
            return faile("非法文件");
        }
        String suffux = fileName.substring(index);
        for (String s : WebConstant.ALLOW_IMPORT) {
            if (s.equals(suffux)) {
                isAllow = true;
                break;
            }
        }
        if (!isAllow) {
            return faile("非法文件");
        }

        try {
            FileInputStream fis = (FileInputStream) file.getInputStream();
            ExcelUtil<TOldCustomer> util = new ExcelUtil<TOldCustomer>(TOldCustomer.class);
            List<TOldCustomer> list = util.importExcel("Sheet1", fis);
            for (TOldCustomer c : list) {
                if (c == null) {
                    continue;
                }

                boolean switchFlag = false;

                String url = PropertyPlaceholder.getProperty("domain");
                String path = PropertyPlaceholder.getProperty("img_dir");

            }
            for (int i = 0; i < list.size(); i++) {

                TOldCustomer oldCustomer = list.get(i);
                oldCustomerService.insertSelective(oldCustomer);

            }


        } catch (IOException e) {
            LOGGER.info("导入excel异常e={}", e);
        }

        String path = request.getSession().getServletContext().getRealPath("positionexcel");
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String urlnew = sdf.format(new Date());
        fileName = urlnew + fileName;
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }


        // 保存
        try {
            file.transferTo(targetFile);

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("保存文件失败e=", e);
        }

        return success("导入成功");
    }

4.同时用到了Excel工具类,ExcelUtil.java

	public   List<T> importExcel(String sheetName, InputStream input) {
		int maxCol = 0;
		List<T> list = new ArrayList<T>();
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(input);
			HSSFSheet sheet = workbook.getSheet(sheetName);
			if (!sheetName.trim().equals("")) {
				sheet = workbook.getSheet(sheetName);// 如果指定sheet名,则取指定sheet中的内容.
			}
			if (sheet == null) {
				sheet = workbook.getSheetAt(0); // 如果传入的sheet名不存在则默认指向第1个sheet.
			}
			int rows = sheet.getPhysicalNumberOfRows();

			if (rows > 0) {// 有数据时才处理
				// Field[] allFields = clazz.getDeclaredFields();// 得到类的所有field.
				List<Field> allFields = getMappedFiled(clazz, null);

				Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();// 定义一个map用于存放列的序号和field.
				for (Field field : allFields) {
					// 将有注解的field存放到map中.
					if (field.isAnnotationPresent(ExcelVOAttribute.class)) {
						ExcelVOAttribute attr = field.getAnnotation(ExcelVOAttribute.class);
						int col = getExcelCol(attr.column());// 获得列号
						maxCol = Math.max(col, maxCol);
						// System.out.println(col + "====" + field.getName());
						field.setAccessible(true);// 设置类的私有字段属性可访问.
						fieldsMap.put(col, field);
					}
				}
			
				for (int i = 1; i < rows; i++) {// 从第2行开始取数据,默认第一行是表头.
					HSSFRow row = sheet.getRow(i);
					// int cellNum = row.getPhysicalNumberOfCells();
					// int cellNum = row.getLastCellNum();
					int cellNum = maxCol;
					T entity = null;
					//System.err.println("cellNum="+cellNum);
					for (int j = 0; j <= cellNum; j++) {
						//System.err.println("j="+j);
						if (row==null) {
							continue;
						}
						HSSFCell cell = row.getCell(j);
						if (cell == null) {
							continue;
						}
						int cellType = cell.getCellType();
						String c = "";
						Integer val;
						//System.err.println("cellType="+cellType);
						if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
							val=(int)cell.getNumericCellValue();
							c = String.valueOf(val);
						} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
							c = String.valueOf(cell.getBooleanCellValue());
						} else {
							c = cell.getStringCellValue();
						}
						//System.err.println("c="+c);
						if (c == null || c.equals("")) {
							continue;
						}
						
						entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在实例则新建.
						// System.out.println(cells[j].getContents());
						Field field = fieldsMap.get(j);// 从map中得到对应列的field.
						if (field == null) {
							continue;
						}
						// 取得类型,并根据对象类型设置值.
						Class<?> fieldType = field.getType();
						//System.err.println("fieldType="+fieldType.toString());
						if (String.class == fieldType) {
							field.set(entity, String.valueOf(c));
						} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
							field.set(entity, Integer.valueOf(c));
						} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
							field.set(entity, Long.valueOf(c));
						} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
							field.set(entity, Float.valueOf(c));
						} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
							field.set(entity, Short.valueOf(c));
						} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
							field.set(entity, Double.valueOf(c));
						} else if (Character.TYPE == fieldType) {
							if ((c != null) && (c.length() > 0)) {
								field.set(entity, Character.valueOf(c.charAt(0)));
							}
						}else{
							System.out.println("未知的字段数据类型fieldType="+fieldType.getClass().toString());
						}

					}
					if (entity != null) {
						list.add(entity);
					}
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return list;
	}
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值