java - 将超链接放入Excel中的图像(Apache POI) - 程序控制台

我可以在Apache POI中为单元设置超链接,但是我不知道如何将超链接放入图像中(我正在使用XSSF)

这是放置单元超链接的功能:

/**
 * Helper function for putting hyperlink into specified cell
 * @param label
 * @param value
 * @param col
 * @param row
 * @param sheet
 */
private static void putImageHyperlink(Cell cell, CellStyle hyperlinkStyle, String value, Workbook wb) {
    try {
        CreationHelper createHelper = wb.getCreationHelper();
        Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
        link.setAddress(value);
        cell.setHyperlink(link);
        cell.setCellStyle(hyperlinkStyle);

        // Put hyperlink value
        cell.setCellValue(value);
    } catch (Exception e) {
        log.severe("Can't create hyperlink : " + Utils.exceptionToString(e));
    }
}


这是将图像放入指定单元格的功能:

    /**
 * Put image into sheet at position [row,col]
 * @param sheet
 * @param col
 * @param row
 * @param imgData
 * @throws Exception
 */
private static void putImage(Workbook wb, Sheet sheet, int col, int row, byte[] imgData) throws Exception {
    try {
        Drawing drawing = sheet.createDrawingPatriarch();
        int pictureIdx = wb.addPicture(imgData, Workbook.PICTURE_TYPE_PICT);

        CreationHelper helper = wb.getCreationHelper();
        ClientAnchor anchor4 = helper.createClientAnchor();

        //set top-left corner of the picture,
        //subsequent call of Picture#resize() will operate relative to it
        anchor4.setCol1(col);
        anchor4.setRow1(row);
        anchor4.setCol2(col+1);
        anchor4.setRow2(row+1);

        drawing.createPicture(anchor4, pictureIdx);
    } catch (Exception ex) {
        log.severe("Exception : " + Utils.exceptionToString(ex));
    }
}


=>如何将超链接放入由命令drawing.createPicture(anchor4,pictureIdx);创建的图片中?

提前致谢!

最佳答案

当查看Excel的存储方式时,似乎图像在XLSX文件的xl\drawings\_rels\drawing1.xml.relsxl\drawings\drawing1.xml部分中的存储方式有所不同:

<Relationship Id="rId1" Target="http://poi.apache.org" TargetMode="External" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"/>

<xdr:cNvPr descr="Picture" id="2" name="Picture 1"> <a:hlinkClick xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="rId1"/> </xdr:cNvPr>

POI尚不支持通过其API添加此类超链接,但是您可以按照以下方式使用底层的低级API,首先为超链接创建关系,然后在Picture-object中将其设置为与超链接的关系:

    PackageRelationship rel = ((XSSFDrawing)patriarch).getPackagePart().addRelationship(
            new URI("http://poi.apache.org"),
            TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
    ((XSSFDrawing)patriarch).addRelation(rel.getId(),new POIXMLDocumentPart());

    CTPictureNonVisual nvPicPr = ((XSSFPicture)picture).getCTPicture().getNvPicPr();
    CTHyperlink hLinkClick = nvPicPr.getCNvPr().addNewHlinkClick();
    hLinkClick.setId(rel.getId());

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。原文地址:https://stackoverflow.com/questions/34171084/

下一篇       上一篇

相关推荐