EasyPoi 自定义数据处理

getRealKey()的作用是把源名替换为英文名,即学生姓名替换为name如此

MapImportHandler

java 复制代码
public class MapImportHandler extends ExcelDataHandlerDefaultImpl<Map<String, Object>> {

    @Override
    public void setMapValue(Map<String, Object> map, String originKey, Object value) {

       map.put(getRealKey(originKey), value != null ? getSexValue(value.toString()) : null);

    }

    private Object getSexValue(Object value){

        if (value.equals("男")){
            return "1";
        }

        if (value.equals("女")){
            return "0";
        }

        return value;
    }

    private String getRealKey(String originKey) {
        if (originKey.equals("学生姓名")) {
            return "name";
        }
        if (originKey.equals("学生性别")) {
            return "sex";
        }
        if (originKey.equals("进校日期")) {
            return "registrationDate";
        }
        return originKey;
    }
}

Controller层

java 复制代码
@CrossOrigin
    @PostMapping("/importStudentsToMapUseHandler")
    public Boolean importStudentsToMapUseHandler(@RequestParam("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            throw new Exception("error file is empty");
        }

        ImportParams params = new ImportParams();
        //设置title所占行数
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setDataHandler(new MapImportHandler());
        List<Map<String, Object>> studentsListMap = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);

        List<Student> studentsList = new ArrayList<>();


        for (Map<String, Object> studentMap : studentsListMap) {

            String name = (String)studentMap.get("name");
            String sex = (String)studentMap.get("sex");
            String registrationDateStr = (String)studentMap.get("registrationDate");

            Student student = new Student();
            student.setName(name);

            student.setSex(Integer.parseInt(sex));


            LocalDate studengLocalDate = LocalDate.parse(registrationDateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDateTime studentRegistrationLocalDateTime = LocalDateTime.of(studengLocalDate, LocalTime.MIDNIGHT);
            student.setRegistrationDate(studentRegistrationLocalDateTime);

            studentsList.add(student);

        }

        return studentService.saveBatch(studentsList);
    }
相关推荐
jiayong239 小时前
Excel基础操作详细文档01
excel
伟贤AI之路14 小时前
原创分享:Markdown 表格导出 Excel/Json - 方便数据处理分析
json·excel·markdown
jiayong2315 小时前
Excel自动化操作详细文档04
运维·自动化·excel
jiayong2316 小时前
Excel高级功能详细文档03
excel
Channing Lewis1 天前
Python读取excel转成html,并且复制excel中单元格的颜色(字体或填充)
python·html·excel
醉卧考场君莫笑2 天前
excel数据统计与数据可视化
信息可视化·excel
weixin_440401692 天前
WPS Excel 宏使用
excel··wps
GalenZhang8882 天前
Excel/WPS 表格数据合并操作指南
excel·wps
海拥✘2 天前
Excel制作跳动爱心动画:一步步创建动态数学心形图
excel
教练、我想打篮球2 天前
127 apache poi3.11 写 word 中内嵌 表格换行的输出
word·excel·docx·换行