EasyPoi导出超链接字段
·
一、定义注解,poi映射类中,字段标该注解,表示需要插入超链接

二、poi映射类中,标注注解,并设置对应的超链接url存储字段

“业务需求名称”这一列,需要导出为超链接,同时指定保存需要跳转url的字段名称

”业务需求名称“关联的url保存在nameUrl字段中,且该字段不出现在导出的excel表中
三、解析待导出的workbook,设置超链接
1)根据查询的数据,塞到poi里里面,构建WorkBook对象
2)解析WorkBook对象,给指定的列插入超链接
public static <T> void handleHyperlink(Class<T> clazz, Workbook workbook, List<T> poiList) {
Map<Integer, String> urlHolderByOrderNum = ExcelUtils.getHyperLinkHolderByOrderNum(clazz);
Sheet sheet = workbook.getSheetAt(0);
for (int i=0; i<poiList.size(); i++) {
T poi = poiList.get(i);
CreationHelper helper = workbook.getCreationHelper();
Row row = sheet.getRow(i + 1);
CollectionUtils.emptyIfNull(urlHolderByOrderNum.entrySet()).forEach(entry -> {
Integer columnIndex = entry.getKey() - 1;
String urlHolderFieldName = entry.getValue();
// 获取超链接地址
String url = null;
try {
Field field = clazz.getDeclaredField(urlHolderFieldName);
field.setAccessible(true);
url = (String) field.get(poi);
} catch (Exception e) {
throw new BusinessException("导出超链接获取失败");
}
if (StringUtils.isEmpty(url)) {
return;
}
// 创建超链接
Cell cell = row.getCell(columnIndex);
Hyperlink link = helper.createHyperlink(HyperlinkType.URL);
link.setAddress(url);
cell.setHyperlink(link);
// 设置单元格样式(蓝色+下划线)
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setUnderline(Font.U_SINGLE);
font.setColor(IndexedColors.BLUE.getIndex());
style.setFont(font);
cell.setCellStyle(style);
});
}
}
public static <T> Map<Integer, String> getHyperLinkHolderByOrderNum(Class<T> clazz) {
Map<Integer, String> urlHolderByOrderNum = new HashMap<>();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
AddHyperLink addHyperLink = declaredField.getAnnotation(AddHyperLink.class);
Excel excel = declaredField.getAnnotation(Excel.class);
if (Objects.nonNull(excel) && StringUtils.isNotEmpty(excel.orderNum())
&& Objects.nonNull(addHyperLink) && StringUtils.isNotEmpty(addHyperLink.urlHolder())) {
urlHolderByOrderNum.put(Integer.valueOf(excel.orderNum()), addHyperLink.urlHolder());
}
}
return urlHolderByOrderNum;
}
更多推荐


所有评论(0)