LoginSignup
0
0

More than 1 year has passed since last update.

Apache POIを使ってセルにリンクを設定する

Posted at

Apache POIを使ってセルにリンクを設定する場合のサンプルを以下に示します。

Workbook workbook = ...;
Cell cell = ...;

// セルにハイパーリンクを設定する
Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.DOCUMENT);
hyperlink.setAddress("destination!A1");
cell.setHyperlink(hyperlink);

// セルに値を設定する
cell.setCellValue("destinationシートのA1へのリンク");

// 文字色を青色にして、アンダーラインを設定する
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setColor(IndexedColors.BLUE.getIndex());
font.setUnderline(Font.U_SINGLE);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);

Excelではリンクを自動設定すると、文字色が青色になってアンダーラインが設定されますが、POIでは自動設定されないため、ここもコーディングする必要があります。したがって文字色とアンダーラインの設定が不要な場合は、サンプルの最後のほうは無視してOKです。

なおこのサンプルを実行したイメージは以下のようになります。

image.png

環境情報: pom.xml抜粋

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
</properties>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0