今天遇到个问题,在excel中插入超链接,用于直接打开表格链接的文件
1. 类似这种,ctrl+鼠标左键能直接打开,下面用easypoi来实现
2. 查看easypoi文档,字段@Excel注解属性 isHyperlink = true 打开超链接插入功能
3. 实际代码实现
- 实体类字段属性开启超链接
@Excel(name = "参数(input)", orderNum = "12", isHyperlink = true)
private String input;
@Excel(name = "返回值(returnInfo)", orderNum = "13", isHyperlink = true)
private String returnInfo;
- 编写属性拦截器
/**
* @author :yepk
* @version :1.0
* @apiNote :用于导出
* @date :2019-04-24-9:25
*/
public class ExcelDataHandler extends ExcelDataHandlerDefaultImpl<ShakerRequestLogInfo> {
@Override
public Hyperlink getHyperlink(CreationHelper creationHelper, ShakerRequestLogInfo obj, String name, Object value) {
Hyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.FILE);
hyperlink.setLabel(name);
hyperlink.setAddress((String) value);
return hyperlink;
}
}
- 导出参数设置数据拦截器
ExportParams params = new ExportParams(String.format("%s-日志", date), last);
params.setDataHandler(new ExcelDataHandler());
- 给对应实体类字段添加 超链接
// 本例子采用绝对路径
String inputPath = "txt/" + System.currentTimeMillis() + "-input.txt";
// 具体逻辑自行书写
info.setInput(inputPath);
5、完整版测试用例
/**
* @author :yepk
* @version :1.0
* @apiNote :测试类
* @date :2023-07-28-15:52
*/
@Data
public class TempBean implements Serializable {
@Excel(name = "序号", orderNum = "0")
private Integer id;
@Excel(name = "标题", orderNum = "1")
private String title;
@Excel(name = "链接", orderNum = "2", isHyperlink = true)
private String path;
public static void main(String[] args) {
List<TempBean> beanList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
TempBean temp = new TempBean();
temp.setId(i + 1);
temp.setTitle("标题" + (i + 1));
temp.setPath("https://www.baidu.com/s?wd=" + i);
beanList.add(temp);
}
ExportParams params = new ExportParams("测试", "测试");
params.setDataHandler(new ExcelDataHandler());
Workbook workbook = ExcelExportUtil.exportExcel(params, TempBean.class, beanList);
try {
OutputStream os = new FileOutputStream("C:\\Users\\yepk\\Desktop\\test.xls");
workbook.write(os);
workbook.close();
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ExcelDataHandler extends ExcelDataHandlerDefaultImpl<TempBean> {
@Override
public Hyperlink getHyperlink(CreationHelper creationHelper, TempBean obj, String name, Object value) {
Hyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
hyperlink.setLabel(name);
hyperlink.setAddress((String) value);
return hyperlink;
}
}