EasyExcel读取excel读复杂表头文件_Eric~阳-CSDN博客_easyexcel解析不规则表头

 最近在项目开发中,遇到的一个excel复杂表头的导入数据库操作,具体怎么做?直接上代码吧!

 1、文件上传。把你要导入的文件上传磁盘某个目录,当然你也可以导入到项目目录下都行。该类的位置就是controller层,给用户提供一个上传文件的接口。

/**     * 文件上传到本地磁盘     * @param file     * @param req     * @param model     * @return     */    @PostMapping("/fileUpload")    public String fileUpload(            @RequestParam("file") MultipartFile file, HttpServletRequest req, Model model){        try {            // 获取文件的全名称            String fileName = file.getOriginalFilename();            String destFileName="D:"+ File.separator+File.separator+fileName;            File destFile = new File(destFileName);            destFile.getParentFile().mkdirs();            System.out.println(destFile);            file.transferTo(destFile);            model.addAttribute("fileName",fileName);            model.addAttribute("path",destFile);        } catch (FileNotFoundException e) {            e.printStackTrace();            return "上传失败," + e.getMessage();        } catch (IOException e) {            e.printStackTrace();            return "上传失败," + e.getMessage();        }        return "thymeleaf/success";    }

2、导入单个excel表,controller层开放接口。

 /**     * 导入单个excel表格数据     * @param path     * @return     * @throws IOException     */    @RequestMapping(value = "/importSingleExcelData")    public String importSingleExcelData(String path) throws IOException {        // 调用导入的方法        importDataService.importSingleExcelData(path);        return "thymeleaf/ok";    }

3、导入excel文件的接口,service层,当然里面到时候你还需要编写导入数据存储到数据库的接口,我这里就没展示出来了。 

public interface ImportDataService {     // 导入单个Excel文件    public void importSingleExcelData(String path) throws IOException; }

 4、导入excel文件的接口实现类,serviceImpl层,同样的到时候将导入数据存储数据库的接口实现类在这里写。

/**     * 导入单个Excel数据     * @param path     * @throws IOException     */    @Override    public void importSingleExcelData(String path) throws IOException {        File file = new File(path);        InputStream inputStream = new FileInputStream(file);        String fileName = file.getName();        if (fileName.endsWith(".xls")) {           String name = fileName.substring(0,fileName.length()-4);            if ("这里是excel文件名称!".equals(name)) {                EasyExcel.read(inputStream, Radiation.class, new ExcelListener(importDataService)).sheet().doRead();            }        }    }

 5、最重要的就是这个ExcelListener,这个是导入excel数据的监听器。

public class ExcelListener extends AnalysisEventListener {     // 导入数据service    public ImportDataService importDataService;     /**     * 无参构造     */    public ExcelListener() {}     /**     * 有参构造,调用导入数据监听器传入service     * @param importDataService     */    public ExcelListener(ImportDataService importDataService) {        this.importDataService = importDataService;    }     private List<Object> list = new ArrayList<Object>();     private Object object = new Object();    WarReserve warReserve = new WarReserve();      @Override    public void invoke(Object object, AnalysisContext context) {         //System.out.println("行:"+context.readRowHolder().getRowIndex());        //System.out.println("对象:"+object);        //System.out.println("Map结构:"+context.readRowHolder().getCellMap());         int sheetNo = context.readSheetHolder().getSheetNo();        if (sheetNo == 0) {            // XXXX表            GoodsReserve goodsReserve = new GoodsReserve();            // 获取行的索引            int index = context.readRowHolder().getRowIndex();            // 获取该行的map数据            Map<Integer, Cell> map = context.readRowHolder().getCellMap();             // excel最后一行备注信息            String remark = "备注:以上为数据填写区域,各项单元格必填。";             // 取指定行列的值            if (index == 1) {                // 取所属辖区和填表日期                String area = context.readRowHolder().getCellMap().get(1).toString();                // 提取省市区                area = area.replaceAll("省(直辖市、自治区)",",").replaceAll("市(州、盟)",",").replaceAll("县(市、区、旗)","").replaceAll(" ","");                // 取填表日期                String tableDate = context.readRowHolder().getCellMap().get(4).toString().replaceAll("填表日期:","").replaceAll(" ","");                System.out.println("内容1:"+area+"=="+tableDate);                warReserve.setArea(area);                warReserve.setTableDate(tableDate);            }else if (index == 3) {                // 取仓库名称, 储备库类型, 编号, 详细地址, 管理单位                String storeName = context.readRowHolder().getCellMap().get(0).toString();                String storeType = context.readRowHolder().getCellMap().get(1).toString();                String number = context.readRowHolder().getCellMap().get(2).toString();                String address = context.readRowHolder().getCellMap().get(3).toString();                String managementUnit = context.readRowHolder().getCellMap().get(4).toString();                System.out.println("内容2:"+storeName+"=="+storeType+"=="+number+"=="+address+"=="+managementUnit);                warReserve.setStoreName(storeName);                warReserve.setStoreType(storeType);                warReserve.setNumber(number);                warReserve.setAddress(address);                warReserve.setManagementUnit(managementUnit);            }else if (index == 6) {                // 取经度, 纬度, 负责人姓名,负责人电话                String longitude = context.readRowHolder().getCellMap().get(0).toString();                String latitude = context.readRowHolder().getCellMap().get(1).toString();                String name = context.readRowHolder().getCellMap().get(2).toString();                String phone = context.readRowHolder().getCellMap().get(3).toString();                System.out.println("内容3:"+longitude+"=="+latitude+"=="+name+"=="+phone);                warReserve.setLongitude(longitude);                warReserve.setLatitude(latitude);                warReserve.setName(name);                warReserve.setPhone(phone);            }else if (index >= 9 && !map.get(0).toString().equals(remark)) {                // 取主要储备物资中名称, 型号, 数量, 计量单位                String goodsName = context.readRowHolder().getCellMap().get(0).toString();                String goodsModel = context.readRowHolder().getCellMap().get(2).toString();                String goodsNumber = context.readRowHolder().getCellMap().get(3).toString();                String goodsUnit = context.readRowHolder().getCellMap().get(4).toString();                System.out.println("内容4:"+goodsName+"=="+goodsModel+"=="+goodsNumber+"=="+goodsUnit);                goodsReserve.setGoodsName(goodsName);                goodsReserve.setGoodsModel(goodsModel);                goodsReserve.setGoodsNumber(goodsNumber);                goodsReserve.setGoodsUnit(goodsUnit);                list.add(goodsReserve);            }else if (map.get(0).toString().equals(remark)){                warReserve.setGoodsReserves(list);                ImportData importData = new ImportData();                importData.setFileName("国家交通战备物资储备库潜力采集表");                String studentJson = JSON.toJSONString(warReserve);                importData.setFileData(studentJson);                importData.setRemarkId(queryImportDataNumber()+1);                importDataService.insertImportData(importData);                System.out.println(warReserve);            }        }    }     @Override    public void doAfterAllAnalysed(AnalysisContext analysisContext) {     }     /**     * 查询导入数据记录条数     */    private int queryImportDataNumber() {        return  importDataService.queryImportDataNumber();    }}

结束语:相信我展示这么多出来大家应该都懂了噢!如果还有问题欢迎大家留言。当然开发中有不妥之处欢迎大家提出了,博主多多改正,谢谢大家的阅读。 


原网址: 访问
创建于: 2021-04-19 17:02:49
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论