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);
    }
相关推荐
LAM LAB3 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下3 天前
Keepalived学习总结
excel
Youngchatgpt3 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好3 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu3 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录3 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu4 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_930707784 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong4 天前
B生所学EXCEL
人工智能·excel