POI给单元格添加超链接(xls,xlsx)

Posted on 2022-08-09 11:47  jiaoqing。  阅读(783)  评论(0)    收藏  举报
package com.topcheer.html;

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

import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test2 {
    public static void main(String[] args) throws IOException {  
        /* !使用POI版本:3.10-FINAL*/  
          
        /* 建立新HSSFWorkbook对象*/  
        XSSFWorkbook workbook = new XSSFWorkbook();
          
        XSSFSheet createSheet = workbook.createSheet("汇总页面");  
        XSSFRow row = createSheet.createRow((short)0);  
          
        /* 连接跳转*/  
        XSSFCell likeCell = row.createCell((short)0);     
      //  XSSFHyperlink link = new XSSFHyperlink(XSSFHyperlink.LINK_URL);// 无法实例化XSSFHyperlink对象
        CreationHelper createHelper = workbook.getCreationHelper();
        XSSFHyperlink  hyperlink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
        // "#"表示本文档    "明细页面"表示sheet页名称  "A10"表示第几列第几行  
        hyperlink.setAddress("#明细页面!A10");  
        likeCell.setHyperlink(hyperlink);  
        // 点击进行跳转  
        likeCell.setCellValue("1");  
          
        /* 设置为超链接的样式*/  
        XSSFCellStyle linkStyle = workbook.createCellStyle();
        XSSFFont cellFont = workbook.createFont();
        cellFont.setUnderline((byte) 1);  
        cellFont.setColor(HSSFColor.BLUE.index);  
        linkStyle.setFont(cellFont);  
        likeCell.setCellStyle(linkStyle);  
          
        /* 建立第二个sheet对象*/  
        XSSFSheet sheet2 = workbook.createSheet("明细页面");  //建立新的sheet对象  
        for (int i = 0; i < 30; i++) {  
            XSSFRow row2 = sheet2.createRow((short)i);  
            XSSFCell cell2 = row2.createCell((short)0);  
            cell2.setCellValue("测试第"+(i+1)+"");  
        }  
          
        /* 输出文件*/  
        FileOutputStream fileOut = new FileOutputStream("D:\\汇总和明细.xlsx");  
        workbook.write(fileOut);  
        fileOut.close();  
    }  

}


原文链接:https://blog.csdn.net/qq_29860591/article/details/105063139

可参考:https://blog.csdn.net/sanpangouba/article/details/78855214

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3