介紹:
對Apache POI 3.9的簡單封裝,實現Excel的導出導入功能。使用Annotation定義導出導入字段。http://jeesite.comhtml
優勢:
- 簡單易用,支持大數量導出,配置簡單,代碼量少。
- 支持Excel 200三、200七、2010(xls、xlsx)格式。
- 支持簡單格式設置,對齊方式,排序等
- 可導出字典類型數據,自定義數據字段類型(例如:部門關聯對象,部門名稱與部門編號互轉)。
- 無需創建導入模板,系統自動生成。
缺點:
- 格式單一,沒法導出格式比較複雜的表格。
- 不能使用模板進行導入,導出。
使用示例:
一、導出實體對象中的annotation的定義(ExcelField說明見:五、ExcelField定義說明):java
- @Entity
- @Table(name = "sys_user")
- public class User extends BaseEntity {
-
- private Long id; // 編號
- ...
- ...
- ...
- private List<Role> roleList = Lists.newArrayList(); // 擁有角色列表
-
- @Id
- @ExcelField(title="ID", type=1, align=2, sort=1)
- public Long getId() {
- return id;
- }
- @ManyToOne
- @ExcelField(title="所屬區域", align=2, sort=10)
- public Area getArea() {
- return area;
- }
- @ManyToOne
- @ExcelField(title="所屬部門", align=2, sort=20)
- public Office getOffice() {
- return office;
- }
- @Length(min=1, max=100)
- @ExcelField(title="姓名", align=2, sort=40)
- public String getName() {
- return name;
- }
- @Length(min=0, max=100)
- @ExcelField(title="用戶類型", align=2, sort=80, dictType="sys_user_type")
- public String getUserType() {
- return userType;
- }
- @ExcelField(title="建立時間", type=0, align=1, sort=90)
- public Date getCreateDate() {
- return createDate;
- }
- @ExcelField(title="最後登陸日期", type=1, align=1, sort=110)
- public Date getLoginDate() {
- return loginDate;
- }
- @ManyToMany
- @ExcelField(title="擁有角色", align=1, sort=800, fieldType=RoleListType.class)
- public List<Role> getRoleList() {
- return roleList;
- }
- }
二、Excel導出示例:git
- public String exportFile(User user) {
- try {
- String fileName = "用戶數據"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
- // 查詢數據
- Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
- // 1:建立Excel導出對象;2:設置數據;3:寫入輸出流;4:臨時數據銷燬
- new ExportExcel("用戶數據", User.class)
- .setDataList(page.getList())
- .write(response, fileName)
- .dispose();
- return null;
- } catch (Exception e) {
- addFlashMessage("導出用戶失敗!失敗信息:"+e.getMessage());
- }
- return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";
- }
三、Excel 導入示例:github
- public String importFile(MultipartFile file) {
- try {
- int successNum = 0;
- int failureNum = 0;
- StringBuilder failureMsg = new StringBuilder();
- // 建立導入Excel對象
- ImportExcel ei = new ImportExcel(file, 1, 0);
- // 獲取傳入Excel文件的數據,根據傳入參數類型,自動轉換爲對象
- List<User> list = ei.getDataList(User.class);
- // 遍歷數據,保存數據
- for (User user : list){
- try{
- if ("true".equals(checkLoginName("", user.getLoginName()))){
- user.setPassword(SystemService.entryptPassword("123456"));
- BeanValidators.validateWithException(validator, user);
- systemService.saveUser(user);
- successNum++;
- }else{
- failureMsg.append("<br/>登陸名 "+user.getLoginName()+" 已存在; ");
- failureNum++;
- }
- }catch(ConstraintViolationException ex){
- failureMsg.append("<br/>登陸名 "+user.getLoginName()+" 導入失敗:");
- List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
- for (String message : messageList){
- failureMsg.append(message+"; ");
- failureNum++;
- }
- }catch (Exception ex) {
- failureMsg.append("<br/>登陸名 "+user.getLoginName()+" 導入失敗:"+ex.getMessage());
- }
- }
- if (failureNum>0){
- failureMsg.insert(0, ",失敗 "+failureNum+" 條用戶,導入信息以下:");
- }
- addFlashMessage("已成功導入 "+successNum+" 條用戶"+failureMsg);
- } catch (Exception e) {
- addFlashMessage("導入用戶失敗!失敗信息:"+e.getMessage());
- }
- return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";
- }
四、Excel 導入模板下載示例app
- public String importFileTemplate() {
- try {
- String fileName = "用戶數據導入模板.xlsx";
- List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser(true));
- // 第三個參數設置爲「2」表示輸出爲導入模板(1:導出數據;2:導入模板)
- new ExportExcel("用戶數據", User.class, 2).setDataList(list).write(response, fileName).dispose();
- return null;
- } catch (Exception e) {
- addFlashMessage("導出用戶失敗!失敗信息:"+e.getMessage());
- }
- return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";
- }
五、ExcelField定義說明:大數據
- /**
- * Copyright © 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- */
- package com.thinkgem.jeesite.common.utils.excel.annotation;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- /**
- * Excel註解定義
- * @author ThinkGem
- * @version 2013-03-10
- */
- @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- public @interface ExcelField {
-
- /**
- * 導出字段名(默認調用當前字段的「get」方法,如指定導出字段爲對象,請填寫「對象名.對象屬性」,例:「area.name」、「office.name」)
- */
- String value() default "";
-
- /**
- * 導出字段標題
- */
- String title();
-
- /**
- * 字段類型(0:導出導入;1:僅導出;2:僅導入)
- */
- int type() default 0;
-
- /**
- * 導出字段對齊方式(0:自動;1:靠左;2:居中;3:靠右)
- */
- int align() default 0;
-
- /**
- * 導出字段字段排序(升序)
- */
- int sort() default 0;
-
- /**
- * 若是是字典類型,請設置字典的type值
- */
- String dictType() default "";
-
- /**
- * 反射類型
- */
- Class<?> fieldType() default Class.class;
-
- }