easyexcel 设置超链接或附件地址

2023-02-18 00:00:00 设置 超链接 附件

easyexcel 设置超链接或附件地址

  • 自定义拦截器
  • 测试方法
  • 结果

自定义拦截器

package com.alibaba.easyexcel.test.demo.write;

import java.util.List;

import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.AbstractCellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;

/** * 自定义拦截器。对第一行第一列的头超链接到:https://github.com/alibaba/easyexcel * * @author Jiaju Zhuang */
public class CustomCellWriteHandler extends AbstractCellWriteHandler { 

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomCellWriteHandler.class);

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
        List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { 
        // 这里可以对cell进行任何操作
        LOGGER.info("第{}行,第{}列写入完成。", cell.getRowIndex(), cell.getColumnIndex());
        if (isHead && cell.getColumnIndex() == 0) {  // 对第一行第一列的头超链接
            CreationHelper createHelper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper();
            Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL);
            hyperlink.setAddress("https://github.com/alibaba/easyexcel");
            cell.setHyperlink(hyperlink);
        }
        if (!isHead && head.getFieldName().equals("filePath")){  // 头为 filePath 的列设置附件相对地址
            CreationHelper createHelper = writeSheetHolder.getSheet().getWorkbook().getCreationHelper();
            Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.FILE); // 类型设置为 FILE
            hyperlink.setAddress("file/tmp/t-1619677433587.xlsx");  // 附件相对地址,必须使用反斜杠
            cell.setHyperlink(hyperlink);
        }
    }

}

测试方法

    @Test
    public void customHandlerWrite() { 
        String fileName = TestFileUtil.getPath() + "customHandlerWrite" + System.currentTimeMillis() + ".xlsx";
        System.out.println(fileName);
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, DemoData.class)
            .registerWriteHandler(new CustomCellWriteHandler())
            .sheet("模板").doWrite(data());
    }

结果

《easyexcel 设置超链接或附件地址》
《easyexcel 设置超链接或附件地址》

参考文档:https://www.yuque.com/easyexcel/doc/easyexcel

    原文作者:Catch.Cat
    原文地址: https://blog.csdn.net/JAVA_Throw/article/details/116374300
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章