<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency>
屬性 | 類型 | 類型 | 說明 |
---|---|---|---|
name | String | null | 列名 |
needMerge | boolean | fasle | 縱向合併單元格 |
orderNum | String | "0" | 列的排序,支持name_id |
replace | String[] | {} | 值得替換 導出是{a_id,b_id} 導入反過來 |
savePath | String | "upload" | 導入文件保存路徑 |
type | int | 1 | 導出類型 1 是文本 2 是圖片,3 是函數,10 是數字 默認是文本 |
width | double | 10 | 列寬 |
height | double | 10 | 列高,後期打算統一使用@ExcelTarget的height,這個會被廢棄,注意 |
isStatistics | boolean | fasle | 自動統計數據,在追加一行統計,把全部數據都和輸出這個處理會吞沒異常,請注意這一點 |
isHyperlink | boolean | false | 超連接,若是是須要實現接口返回對象 |
isImportField | boolean | true | 校驗字段,看看這個字段是否是導入的Excel中有,若是沒有說明是錯誤的Excel,讀取失敗,支持name_id |
exportFormat | String | "" | 導出的時間格式,以這個是否爲空來判斷是否須要格式化日期 |
importFormat | String | "" | 導入的時間格式,以這個是否爲空來判斷是否須要格式化日期 |
format | String | "" | 時間格式,至關於同時設置了exportFormat 和 importFormat |
databaseFormat | String | "yyyyMMddHHmmss" | 導出時間設置,若是字段是Date類型則不須要設置 數據庫若是是string 類型,這個須要設置這個數據庫格式,用以轉換時間格式輸出 |
numFormat | String | "" | 數字格式化,參數是Pattern,使用的對象是DecimalFormat |
imageType | int | 1 | 導出類型 1 從file讀取 2 是從數據庫中讀取 默認是文件 一樣導入也是同樣的 |
suffix | String | "" | 文字後綴,如% 90 變成90% |
isWrap | boolean | true | 是否換行 即支持\n |
mergeRely | int[] | {} | 合併單元格依賴關係,好比第二列合併是基於第一列 則{1}就能夠了 |
mergeVertical | boolean | fasle | 縱向合併內容相同的單元格 |
實體類:前端
import cn.afterturn.easypoi.excel.annotation.Excel; import java.util.Date; public class Person { @Excel(name = "姓名", orderNum = "0") private String name; @Excel(name = "性別", replace = {"男_1", "女_2"}, orderNum = "1") private String sex; @Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "2") private Date birthday; public Person(String name, String sex, Date birthday) { this.name = name; this.sex = sex; this.birthday = birthday; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){ ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){ defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){ defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) { Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list); if (workbook != null); downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { throw new NormalException(e.getMessage()); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){ if (StringUtils.isBlank(filePath)){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); }catch (NoSuchElementException e){ throw new NormalException("模板不能爲空"); } catch (Exception e) { e.printStackTrace(); throw new NormalException(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){ if (file == null){ return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); }catch (NoSuchElementException e){ throw new NormalException("excel文件不能爲空"); } catch (Exception e) { throw new NormalException(e.getMessage()); } return list; }
對的,沒看錯,這就能夠導出導入了,看起來代碼挺多,實際上是提供了多個導入導出方法而已java
導出實現類,使用@ExcelTarget註解與@Excel註解:node
import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.annotation.Excel; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import com.fasterxml.jackson.annotation.JsonFormat; import com.jn.ssr.superrescue.annotation.Translate; import com.jn.ssr.superrescue.cache.DictCache; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.net.URLEncoder; import java.util.*; import java.util.stream.Collectors; public class FileUtil { private static Logger log = LogManager.getLogger(FileUtil.class); public static final int BIG_DATA_EXPORT_MIN = 50000; public static final int BIG_DATA_EXPORT_MAX = 2000000; //excel處理註解set集合 public static HashSet<String> transClassSet = new HashSet(); public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) { ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, title, sheetName); } /** * 導出函數 * * @param list 導出集合 * @param title 標題 * @param sheetName sheet名 * @param pojoClass 映射實體 * @param fileName 文件名 * @param response httpresponce * size若是過大 需採用poi SXSSF */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) { //判斷該類是否已經處理過excel註解 long startTime = System.currentTimeMillis(); if (!transClassSet.contains(String.valueOf(pojoClass))) { initProperties(pojoClass); transClassSet.add(String.valueOf(pojoClass)); } defaultExport(list, pojoClass, fileName, response, title, sheetName); log.info("此文件[{}]導出耗時:{}ms", fileName, (System.currentTimeMillis() - startTime)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, String title, String sheetName) { Workbook workbook = null; ExportParams exportParams = new ExportParams(title, sheetName); if (list != null && list.size() > BIG_DATA_EXPORT_MAX) { sizeBeyondError(response); return; } else if (list != null && list.size() > BIG_DATA_EXPORT_MIN) { log.info("文件過大采用大文件導出:" + list.size()); for (int i = 0; i < (list.size() / BIG_DATA_EXPORT_MIN + 1) && list.size() > 0; i++) { log.info("當前切片:" + i * BIG_DATA_EXPORT_MIN + "-" + (i + 1) * BIG_DATA_EXPORT_MIN); List<?> update = list.stream().skip(i * BIG_DATA_EXPORT_MIN).limit(BIG_DATA_EXPORT_MIN).collect(Collectors.toList()); exportParams.setCreateHeadRows(true); exportParams.setMaxNum(BIG_DATA_EXPORT_MIN * 2 + 2); workbook = ExcelExportUtil.exportBigExcel(exportParams, pojoClass, update); } ExcelExportUtil.closeExportBigExcel(); } else { workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list); } if (workbook == null) return; downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // workbooks.forEach(e -> e.write(response.getOutputStream())); workbook.write(response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); try { response.getWriter().println("{\"code\":597,\"message\":\"export error!\",\"data\":\"\"}"); response.getWriter().flush(); } catch (Exception e1) { e1.printStackTrace(); } finally { closeIo(response); } } } /** * 文件過大,不容許導出 * * @param response */ private static void sizeBeyondError(HttpServletResponse response) { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); try { response.getWriter().println("{\"code\":599,\"message\":\"文件過大!\",\"data\":\"\"}"); response.getWriter().flush(); } catch (Exception e1) { e1.printStackTrace(); } finally { closeIo(response); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null) ; downLoadExcel(fileName, response, workbook); } public static < T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (StringUtils.isBlank(filePath)) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); } catch (NoSuchElementException e) { e.printStackTrace(); System.out.println("模版爲空"); } catch (Exception e) { e.printStackTrace(); } return list; } public static < T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (file == null) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); } catch (NoSuchElementException e) { e.printStackTrace(); System.out.println("文件爲空"); } catch (Exception e) { e.printStackTrace(); } return list; } /** * 代理初始化該類的註解 * * @param cl */ public synchronized static void initProperties(Class cl) { try { Field[] fields = cl.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Excel.class)) { field.setAccessible(true); Excel excel = field.getAnnotation(Excel.class); InvocationHandler h = Proxy.getInvocationHandler(excel); Field hField = h.getClass().getDeclaredField("memberValues"); // 由於這個字段事 private final 修飾,因此要打開權限 hField.setAccessible(true); // 獲取 memberValues Map memberValues = (Map) hField.get(h); //判斷是否有轉義註解,將字典添加到excel replace屬性中 if (field.isAnnotationPresent(Translate.class)) { Translate translate = field.getAnnotation(Translate.class); String dicName = translate.dicName(); Map dicMap = DictCache.getProperties(dicName); if (dicMap == null) { continue; } String[] replace = new String[dicMap.size()]; List<String> replaceList = new ArrayList<>(); dicMap.forEach((key, val) -> { replaceList.add(val + "_" + key); }); for (int i = 0; i < dicMap.size(); i++) { replace[i] = replaceList.get(i); } memberValues.put("replace", replace); } //json格式化與JsonFormat統一,目前暫用於時間 if (field.isAnnotationPresent(JsonFormat.class)) { JsonFormat jsonFormat = field.getAnnotation(JsonFormat.class); if (StringUtils.isNotEmpty(jsonFormat.pattern())) { memberValues.put("format", jsonFormat.pattern()); } } } } } catch (Exception e) { e.printStackTrace(); } } /** * 關閉writer * * @param response */ private static void closeIo(HttpServletResponse response) { try { if (response.getWriter() != null) { response.getWriter().close(); } } catch (Exception e) { e.printStackTrace(); } } }
使用VUE前端數據導出實現類:web
import excel from '../../../utils/export'
var exportExcel = {};
exportExcel.exportData=function (params) {
var str = '&';
for(key in params){
str+= key+'='+params[key]+'&';
}
//alert(nodePath+'/export?token='+window.localStorage.user+str);
console.log(nodePath+'/export?token='+window.localStorage.user+str);
window.location.href = nodePath+'/export?token='+window.localStorage.user+str;
}
module.exports = exportExcel;
在VUE頁面中的導出:spring
exportExcel(){
console.log(22222);
let param = {
url: '/automaticCar/export',
params:JSON.stringify(this.ruleForm)
};
excel.exportData(param);
},
@RequestMapping("export") public void export(HttpServletResponse response){ //模擬從數據庫獲取須要導出的數據 List<Person> personList = new ArrayList<>(); Person person1 = new Person("路飛","1",new Date()); Person person2 = new Person("娜美","2", DateUtils.addDate(new Date(),3)); Person person3 = new Person("索隆","1", DateUtils.addDate(new Date(),10)); Person person4 = new Person("小狸貓","1", DateUtils.addDate(new Date(),-10)); personList.add(person1); personList.add(person2); personList.add(person3); personList.add(person4); //導出操做 FileUtil.exportExcel(personList,"花名冊","草帽一夥",Person.class,"海賊王.xls",response); } @RequestMapping("importExcel") public void importExcel(){ String filePath = "F:\\海賊王.xls"; //解析excel, List<Person> personList = FileUtil.importExcel(filePath,1,1,Person.class); //也可使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)導入 System.out.println("導入數據一共【"+personList.size()+"】行"); //TODO 保存數據庫 }
導出結果再添加一行,執行,輸出導入數據行數數據庫