使用反射來給Excel表添加字段
1、實體類中字段如下:
@Data
@Table(name = "T_ZD") public class Site { /** * 主鍵 */ @Id @KeySql(sql = "select T_ZD_SEQ.nextval from dual", order = ORDER.BEFORE) @Column(name = "ID") private Integer id;
。。。。
@Transient @Excel(name = "線路名稱",width = 30,isColumnHidden = false) private String routeName; }
其中@Excel注解的isColumnHidden屬性默認為false,即顯示
2、我們可以通過反射來將該isColumnHidden屬性值由false改為true
@RequestMapping(value = "templateExport") public void templateExport(String fileName, String bean, HttpServletResponse response) { try { Field routeName = Site.class.getDeclaredField("routeName"); Excel excel = routeName.getAnnotation(Excel.class); InvocationHandler invocationHandler = Proxy.getInvocationHandler(excel); Field excelField = invocationHandler.getClass().getDeclaredField("memberValues"); excelField.setAccessible(true); Map memberValues = (Map) excelField.get(invocationHandler); memberValues.put("isColumnHidden", true); } catch (Exception e) { e.printStackTrace(); } siteService.templateExport(fileName,bean,response); }
使用反射刪除Excel表的字段
1、實體類Route
@Data @Table(name = "T_XL") public class Route { /** * 主鍵 */ @Id @KeySql(sql = "select T_XL_SEQ.nextval from dual", order = ORDER.BEFORE) @Column(name = "ID") private Integer id;
。。。。
//錯誤信息 @Transient @Excel(name = "錯誤信息", width = 50, isColumnHidden = true) private String errorMsg; }
2、我們可以通過反射來將該isColumnHidden屬性值由true改為false
@Async public void checkDataIsExist(Route route, List<Route> addList, List<Route> updateList, List<Route> errorList) throws Exception { 。。。。。if(null != enterpriseId){ 。。。。 }else{ EasyPoiUtil<Route> easyPoiUtil = new EasyPoiUtil<>(); easyPoiUtil.t = route; //顯示錯誤信息的列 easyPoiUtil.hideColumn("errorMsg", false); route.setErrorMsg("未查詢到企業信息"); errorList.add(route); } }
3、工具類
public class EasyPoiUtil<T> { /** * 需要被反射的對象,使用泛型規范傳入對象 */ public T t; /** * 動態更改EasyPoi中控制列顯示的值 * * @param columnName 需要轉換的列屬性名稱 * @param target 默認true(不顯示) * @throws NoSuchFieldException * @throws IllegalAccessException */ public void hideColumn(String columnName, Boolean target) throws Exception { if (t == null) { throw new ClassNotFoundException("未找到目標類"); } if (StringUtils.isEmpty(columnName)) { throw new NullPointerException("傳入的屬性列名為空"); } if (target == null) { target = true; } //獲取目標對象的屬性值 Field field = t.getClass().getDeclaredField(columnName); //獲取注解反射對象 Excel excelAnion = field.getAnnotation(Excel.class); //獲取代理 InvocationHandler invocationHandler = Proxy.getInvocationHandler(excelAnion); Field excelField = invocationHandler.getClass().getDeclaredField("memberValues"); excelField.setAccessible(true); Map memberValues = (Map) excelField.get(invocationHandler); memberValues.put("isColumnHidden", target); } }