poi3.17导出excel添加附件解决办法

快速指南:apache poi quick-guid
在导出excle时候需要添加一些附件,可以通过超链接来实现
  • 定义超链接的样式
private CellStyle createHyperlinkStyle(HSSFWorkbook hssfWorkbook){
	CellStyle hLinkStyle = hssfWorkbook.createCellStyle();
	Font hLinkFont = hssfWorkbook.createFont();
	hLinkFont.setUnderline(Font.U_SINGLE);
	hLinkFont.setColor(IndexedColors.BLUE.getIndex());
	hLinkStyle.setFont(hLinkFont);
	return hLinkStyle;
}
  • 给单元格设置超链接
//文件保存全路径
String url = /home/attachement/test.xls
//文件名称,禁用中文,超链接导致乱码,链接不到
String fileName = "test.xls";
rowCell.setCellValue("导出单元格显示的名称");
HSSFCreationHelper creationHelper = hssfWorkbook.getCreationHelper();
//创建文件超链接
HSSFHyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.FILE);
//把附件从远程服务器下载到本地
String targetUrl = download(url, fileName);
hyperlink.setAddress(url);
rowCell.setHyperlink(hyperlink);
rowCell.setCellStyle(createHyperlinkStyle(hssfWorkbook));
private String download(String url, String fileName) {
        //下载到本地电脑
        String rootPath = "D:/attachment/download/";
        String fullPath = rootPath + fileName;
        File f = new File(url);
        InputStream in = null;
        OutputStream os = null;
        try {
            in = new FileInputStream(f);
            byte[] b = new byte[512];
            int len = 0;
            File file = new File(fullPath);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.mkdirs();
                }
                f.mkdir();
            }

            os = new FileOutputStream(file);
            while ((len = in.read(b)) != -1) {
                os.write(b, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return fullPath;
    }

最后效果图:
在这里插入图片描述

在数据大的情况下,频繁的下载到本地肯定是行不通的,最好是有自己文件服务器,超链接下载地址,这样可以不用下载到本地电脑,速度快,效率高。

以上个人观点,不喜勿喷!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值