如何使用 java-apache poi 创建 100 张的超链接

问题描述 投票:0回答:1

我正在创建 Mainsheet 和 100 个工作表。主工作表应该有 100 个各个工作表的超链接以及工作表名称?我如何使用 apache POI 来做到这一点。

P.S:如果问题不清楚/需要更多信息,请在降级之前在评论中询问我

java excel apache hyperlink apache-poi
1个回答
0
投票

查看示例代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class HyperlinkExample {
    public static void main(String[] args) {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet mainSheet = workbook.createSheet("MainSheet");

            // Create a cell style for hyperlinks
            CellStyle hyperlinkStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setUnderline(Font.U_SINGLE);
            font.setColor(IndexedColors.BLUE.getIndex());
            hyperlinkStyle.setFont(font);

            for (int i = 1; i <= 100; i++) {
                XSSFSheet sheet = workbook.createSheet("Sheet" + i);

                // Create a hyperlink to the sheet
                String sheetName = "Sheet" + i;
                XSSFHyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.DOCUMENT);
                hyperlink.setAddress("'" + sheetName + "'!A1"); // Link to cell A1 in the sheet
                hyperlink.setTooltip("Go to " + sheetName);

                // Create a row and a cell in the main sheet
                XSSFRow row = mainSheet.createRow(i - 1);
                XSSFCell cell = row.createCell(0);
                cell.setCellValue(sheetName);
                cell.setCellStyle(hyperlinkStyle);
                cell.setHyperlink(hyperlink);
            }

            // Write the workbook to a file
            try (FileOutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
                workbook.write(fileOut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.