EasyExcel導入工具(SpringMVC下使用)


easyExcel:由阿里巴巴公司開發,由github托管

github上有詳細使用文檔

github地址:https://github.com/alibaba/easyexcel/blob/master/quickstart.md

 

 

導入

1、模型類:可以是實體類

主要是@ExcelProperty注解

value:對應字段

index:對應導入模板是第幾列(從0開始)

@ExcelProperty(value = "name", index = 0)

 

推薦使用有模型,因為導入模板如果有變化,index可以隨時改變

 

2、Controller接收導入文件

//批量導入(有模型)
    @RequestMapping("batchImport") public ModelAndView batchImport(@RequestParam(value = "file", required=true)MultipartFile file) { ModelAndView mv=new ModelAndView(); mv.setView(Jackson2Util.jsonView()); InputStream in = null; try { in = file.getInputStream(); // 解析每行結果在listener中處理
            AnalysisEventListener listener = new ExcelListener(vehicleInfoService); ExcelReader excelReader = new ExcelReader(in, ExcelTypeEnum.XLSX, null, listener); //(第幾個sheet,表頭所在行數,表格對應實體類) excelReader.read(new Sheet(1, 1, ExcelCardIssueVehicleInfo.class)); mv.addObject("res", "0"); } catch(Exception e) { logger.error("批量導入失敗!", e); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return mv; }

 

 

3、解析每行數據並入庫

public class ExcelListener extends AnalysisEventListener { private CardIssueVehicleInfoService cardIssueVehicleInfoService; public ExcelListener(CardIssueVehicleInfoService cardIssueVehicleInfoService) { super(); this.cardIssueVehicleInfoService = cardIssueVehicleInfoService; } private List<CardIssueVehicleInfo> datas = new ArrayList<CardIssueVehicleInfo>(); //每解析一行數據就走一遍invoke()方法 public void invoke(Object object, AnalysisContext context) { //轉為導入模型類 ExcelCardIssueVehicleInfo excel = (ExcelCardIssueVehicleInfo)object; CardIssueVehicleInfo vehicleInfo = new CardIssueVehicleInfo(); try { //導入模型類轉為對應數據庫的實體類:可以是同一個實體類  BeanUtils.copyProperties(vehicleInfo, excel); datas.add(vehicleInfo); //數據存儲到list,供批量導入處理,或后續自己業務邏輯處理。  } catch (Exception e) { e.printStackTrace(); } } //解析完所有Excel數據后,走此方法 public void doAfterAllAnalysed(AnalysisContext context) { try{ //入庫  cardIssueVehicleInfoService.batchInsert(datas); } catch(Exception e) { logger.error("批量導入失敗!", e); } datas.clear();//解析結束銷毀不用的資源  } }

 

 

遇到問題及解決方案:

1、模型(實體類)支持String和int類型,不支持Short類型

 

2、在ExcelListener 類中,Spring注入Service層,會無法注入

解決:在Controller層,將已注入的Service,傳入ExcelListener中

 AnalysisEventListener listener = new ExcelListener(vehicleInfoService);

 

並在ExcelListener的構造器中接收

public ExcelListener(CardIssueVehicleInfoService cardIssueVehicleInfoService) { super(); this.cardIssueVehicleInfoService = cardIssueVehicleInfoService; }

 

3、poi.jar和poi-ooxml.jar的版本一定要一致(easyExcel依賴poi),不然會報錯


4、easyExcel基於POI的,遇到的報錯,都可以按照POI的錯誤搜索解決辦法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM