Java利用Reflect實現(xiàn)封裝Excel導(dǎo)出工具類
最近遇到一個需求,需要對頁面的列表數(shù)據(jù)做導(dǎo)出操作,考慮了很多實現(xiàn)方案之后,最終選擇了hutool的ExcelWriter + Spring自帶的ReflectionUtils工具類來實現(xiàn)這個功能,采用這種方式的主要原因是對現(xiàn)有代碼改動較少,并且可以無縫切入系統(tǒng),實現(xiàn)各個模塊的導(dǎo)出操作,設(shè)計思路如下:
如上圖所示,首先我們定義一個接口,此接口完成Excel導(dǎo)出功能,在ExcelExportService 中實現(xiàn)功能。
話不多說,上代碼:
定義ExcelExportEnum
在導(dǎo)出Excel之前,我們需要先定義ExcelExportEnum,此枚舉存儲了我們后端需要導(dǎo)出的模塊和模板名稱
@Getter @RequiredArgsConstructor public enum ExcelExportEnum { /** * 模塊 */ MODULE_A("moduleAService", "模塊A"); private final String key; private final String name; }
定義導(dǎo)出方法
校驗入?yún)?/h3>
首先,我們需要對入?yún)⑦M行校驗,查看傳入的 MODULE_NAME
是否和后端Enum的一致,并且我們需要對參數(shù)中的自定義方法名進行提取,我們通過ExcelExportEnum來獲取導(dǎo)出的module的Service名稱
if (!map.containsKey(MODULE_NAME)) { throw new BaseException("缺少參數(shù):moduleName"); } String moduleName = map.get(MODULE_NAME).toString(); if (!EnumUtil.contains(ExcelExportEnum.class, moduleName)) { throw new BaseException("模塊查找失敗"); } String functionName = DEFAULT_FUNCTION_NAME; //如果傳了自定義方法名 if (map.containsKey(CUSTOM_FUNCTION_NAME)) { functionName = map.get(CUSTOM_FUNCTION_NAME).toString(); } String serviceName = ExcelExportEnum.valueOf(moduleName).getKey(); String tableName = ExcelExportEnum.valueOf(moduleName).getName();
利用java反射獲取Service中的所有method
Map<String, Method> methodMap = Arrays.stream(SpringContextHolder.getBean(serviceName).getClass().getMethods()).collect(Collectors.toMap(Method::getName, Function.identity(), (key1, key2) -> key2));
在上述代碼中SpringContextHolder.getBean(serviceName).getClass().getMethods()
方法,首先通過getBean
來獲取 第一步中得到的ServiceName的Java bean。然后通過Class.getMethods()方法獲取此service中的所有方法
最后,使用Arrays.stream方法,將module對應(yīng)的Service中的所有method獲取到,并放入methodMap中,供后續(xù)代碼使用
提取method中的入?yún)ο?,獲取其Class
Object o; try { o = methodMap.get(functionName).getParameterTypes()[0].getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new BaseException(e); }
通過Method.getParameterTypes()方法,將第二步中獲取的method的入?yún)⒌腃lass取到,并賦值給對象Object o,供后續(xù)調(diào)用分頁列表接口傳遞入?yún)⑵ヅ銫lass使用
傳入?yún)?shù),調(diào)用導(dǎo)出方法
Map<String, Object> param = (Map<String, Object>) map.computeIfAbsent(PARAM, k -> new HashMap<String, Object>(4)); param.put("limit", -1); CopyOptions copyOptions = new CopyOptions(); copyOptions.setIgnoreError(true); PageUtils page = (PageUtils) methodMap.get(functionName).invoke(SpringContextHolder.getBean(serviceName), BeanUtil.mapToBean(param, o.getClass(), true, copyOptions)); if (CollUtil.isEmpty(page.getList())) { throw new BaseException("數(shù)據(jù)獲取失敗"); } Object resultObject = page.getList().get(0); ExcelUtils utils = new ExcelUtils(resultObject.getClass()); utils.exportExcel(page.getList(), response, tableName, moduleName);
可以看到,在上述導(dǎo)出方法中,我們使用了Method.invoke方法,并且設(shè)置轉(zhuǎn)義忽略
注意事項
使用hutool工具包輸出到流
// 通過工具類創(chuàng)建writer,默認創(chuàng)建xls格式 ExcelWriter writer = ExcelUtil.getWriter(); //創(chuàng)建xlsx格式的 //ExcelWriter writer = ExcelUtil.getWriter(true); // 一次性寫出內(nèi)容,使用默認樣式,強制輸出標題 writer.write(rows, true); //out為OutputStream,需要寫出到的目標流 writer.flush(out); // 關(guān)閉writer,釋放內(nèi)存 writer.close();
注意 ExcelUtil.getWriter()
默認創(chuàng)建xls格式的Excel,因此寫出到客戶端也需要自定義文件名為XXX.xls,否則會出現(xiàn)文件損壞的提示。 若想生成xlsx格式,請使用ExcelUtil.getWriter(true)
創(chuàng)建。
到此這篇關(guān)于Java利用Reflect實現(xiàn)封裝Excel導(dǎo)出工具類的文章就介紹到這了,更多相關(guān)Java Reflect封裝Excel導(dǎo)出工具類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux系統(tǒng)下查看jdk版本、路徑及配置環(huán)境變量
在Linux系統(tǒng)中,配置JDK環(huán)境變量是非常重要的,它可以讓你在終端中直接使用Java命令,這篇文章主要給大家介紹了關(guān)于linux系統(tǒng)下查看jdk版本、路徑及配置環(huán)境變量的相關(guān)資料,需要的朋友可以參考下2024-01-01Spring需要三個級別緩存解決循環(huán)依賴原理解析
這篇文章主要為大家介紹了Spring需要三個級別緩存解決循環(huán)依賴原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02