SSH框架实现excel文件的上传及下载功能【完整代码附上】

229 阅读2分钟

使用struts2中的文件上传与下载功能,需要先导入两个jar文件,一个是commons-fileupload.jar,另一个是commons-io.jar,如下:

在这里插入图片描述
struts2 实现excel上传:

<jsp页面>

<form method="post" id="uploadForm">
<input type="file" id="file" name="file"/>
<input type="button" onclick="ajax('${pageContext.request.contextPath}/upload/excel.html')" value="开始上传">
</form>

<js引用>

function ajax(url){
	var file=document.getElementById('file').files[0];
	if(file==undefined){
		alert('请选择文件');
		return
	}
    var data = new FormData();
    data.append("file", file);
    $.ajax({
        type: 'post',
        url: url,
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            alert(data.msg);
        }, error: function () {
            alert("上传失败");
        },
    });
}

<工具类util>

public class ExcelUtils {
	
	public static List<Map<String,Object>> excelToMap(Map<String,Object> map, File file){
        String fileType =file.getName().substring(file.getName().lastIndexOf(".") + 1);
        Workbook workbook = null;
        try {
            if (fileType.equals("xls")) {
                workbook = new HSSFWorkbook(new FileInputStream(file));
            } else {
                workbook = new XSSFWorkbook(new FileInputStream(file));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //开始读取文件
        Sheet sheet=workbook.getSheetAt(0);
        //读取列头
        Row titleRow=sheet.getRow(0);
        Map<String,Integer> keyMap=new HashMap<>();
        for(int i=0;i<=titleRow.getLastCellNum();i++){
            String cellText=transString(titleRow.getCell(i));
            if(map.containsKey(cellText)){
                String key=map.get(cellText).toString();
                keyMap.put(key,i);
            }
        }
        List<Map<String,Object>> result=new ArrayList<>();
        for(int i=sheet.getFirstRowNum()+1;i<sheet.getPhysicalNumberOfRows();i++){
            Map<String,Object> temp=new HashMap<>();
            for(Iterator<String> iterator=keyMap.keySet().iterator();iterator.hasNext();){
                String key=iterator.next().toString();
                temp.put(key,transString(sheet.getRow(i).getCell(keyMap.get(key))));
            }
            result.add(temp);
        }
        return result;
    }

    public static <T> List<T> excelToBean(Class clazz,Map<String,Object> map, File file){
        List<Map<String,Object>> list=excelToMap(map,file );
        Field[] fields=clazz.getDeclaredFields();
        List<T> result=new ArrayList<>();
        for(Map<String,Object> temp:list) {
            try {
                Object obj=clazz.newInstance();
                for (Field field : fields) {
                    String fieldName = field.getName();
                    if (temp.containsKey(fieldName)){
                        field.setAccessible(true);
                        String dataType=field.getType().getTypeName();
                        Object value=temp.get(fieldName);
                        if(value!=null){
                        if(dataType.equals("java.lang.String")){
                        	field.set(obj,value.toString());
                        }else if(dataType.equals("java.lang.int")){
                        	field.set(obj,Integer.valueOf(value.toString()));
                        }
                        }
                    }
                }
                result.add((T)obj);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String transString(Cell cell){
        String value;
        try {
            value=cell.toString();
            if(value.indexOf(".")>-1){
                DecimalFormat df = new DecimalFormat("#");//转换成整型
                value=df.format(cell.getNumericCellValue());
            }
        }catch (Exception e){
            value="空";
        }
        return value;
    }
}

<UploadAction文件>

public class UploadAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private UserDao userDao;
	private TeacherDao teacherDao;
	private StudentDao studentDao;
	private File file;
	/**
	*省略实体类的get set方法
	*/
	
	// 执行上传功能
	public void upload() {
		int countIng=0;
		int endCount=0;
		int startCount=0;
		// excel列名与数据model的对应关系映射
		// key为excel列名value为实体名称(例如学生Excel表中的列名学生对于User实体中的username)
		// 填写对应关系,如果对应不上,不会填充对应对象
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("姓名", "username");
			map.put("学号", "codenum");
			map.put("班级编号", "banjinum");
			map.put("角色", "role");
			map.put("是否禁用", "userlock");
			// 返回excel中的数据,以列表形式返回,并封装内部转换,自动将对象转换填充,需要使用泛型填充 如User
			// 方法的第一个参数是泛型的类型 如User的类是User.class
			List<User> list = ExcelUtils.excelToBean(User.class, map, getFile());
			// 返回的是一个列表,可以将列表中的数据保存到数据库等
			startCount=list.size();
			List<User> date = userDao.getAllUser();
			//下面这种写法,实例化就是不支持,具体不知道是什么原因
			/*List<String> hasUser = date.stream().map(x->x.getCodenum()).collect(Collectors.toList());*/
			List<String> hasUser=new ArrayList<String>();
			for(User user:date){
				hasUser.add(user.getCodenum());
			}
			for (User user : list) {
				if (hasUser.contains(user.getCodenum())) {
					// 学号已存在
					countIng++;
				} else {
					userDao.insertUser(user);
					// 联动添加到对应的techer表与student表中
					if (user.getRole().equals("3")) {
						Teacher teacher = new Teacher();
						teacher.setName(user.getUsername());
						teacher.setClassid(user.getCodenum());
						teacherDao.insertTea(teacher);
					} else if (user.getRole().equals("2") || user.getRole().equals("4")) {
						Student stu = new Student();
						stu.setClassnum(user.getCodenum());
						stu.setRole(user.getRole());
						stu.setName(user.getUsername());
						studentDao.insertStu(stu);
					}
				}
			}
		} catch (Exception e) {
			Util.ajaxResponse(500, "导入失败");
		}
		if(countIng>0){
			endCount=startCount-countIng;
			Util.ajaxResponse(200, "导入失败!数据共有"+countIng+"条重复,成功录入"+endCount+"条!");
		}
		else{
			Util.ajaxResponse(200, "导入成功!录入"+startCount+"条");
		}
	}

}

<struts-upload.xml配置文件>

<struts>
	<package name="manage_upload" namespace="/upload" extends="struts-default">
		<action name="excel" method="upload" class="manage.action.UploadAction" />
	</package>

</struts>

下期更新实现excel的导入下载功能,敬请期待哦!