Java使用POI读取Excel名称管理器

news2024/9/29 1:19:11

文章目的

本文主要介绍如何使用poi读取到Excel的名称管理器中的内容。并且定位到单元格。

在企业的开发中可能需要通过名称管理器定位到某个单元格,然后在单元格上生成签名。

环境配置

Java:Jdk1.8

poi:5.2.3

maven依赖(pom.xml):

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

        <!-- 以下依赖非必须,可根据项目情况选择性依赖 -->
        <!-- poi案例代码,可以去掉 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-examples</artifactId>
            <version>5.2.3</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.15</version>
        </dependency>

        <!-- 使用slf4j 作为日志门面 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.36</version>
        </dependency>
        <!-- 使用 log4j2 的适配器进行绑定 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>

        <!-- log4j2 日志门面 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.2</version>
        </dependency>
        <!-- log4j2 日志实面 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.2</version>
        </dependency>

        <!-- log4j2-异步日志依赖 -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>3.4.4</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.9.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

实现思路

poi的WorkBook有个getNames方法可以读到名称。

Excel操作

Excel的名称在下图中新建

参考代码

以下代码用于得到单元格引用对象(CellReference)

@Slf4j
public class PoiExcelUtil {

    /**
     * 返回Excel名称管理器中所有名称对应的单元格引用
     *
     * @param path Excel工作簿路径
     * @return List<CellReference>
     */
    public static List<CellReference> listNameCell(String path) throws IOException {
        List<CellReference> result = null;
        if (StrUtil.isNotBlank(path)) {
            log.info("excelFilePath:{}", path);
            Workbook book = new XSSFWorkbook(new FileInputStream(path));
            result = listNameCell(book);
            book.close();
        }
        return result;
    }

    /**
     * 返回Excel名称管理器中所有名称对应的单元格引用
     *
     * @param book Excel工作簿对象
     * @return List<CellReference>
     */
    public static List<CellReference> listNameCell(Workbook book) throws IOException {
        List<CellReference> result = null;
        // 打开Excel文件
        if (book != null && book.getAllNames() != null) {
            result = new ArrayList<>(book.getAllNames().size());
            // 获取所有的名称管理器
            for (Name namedRange : book.getAllNames()) {
                String refersToFormula = namedRange.getRefersToFormula();
                CellReference cellReference = new CellReference(refersToFormula);
                result.add(cellReference);
            }
        }
        return result;
    }

    /**
     * 根据名称得到名称管理器中的名称单元格引用
     *
     * @param filePath
     * @param nameName
     * @return CellReference
     */
    public static CellReference getNameCell(String filePath, String nameName) throws IOException {
        CellReference result = null;
        log.info("excelFilePath:{},nameName:{}", filePath, nameName);
        if (StrUtil.isNotBlank(filePath) && StrUtil.isNotBlank(nameName)) {
            Workbook book = new XSSFWorkbook(new FileInputStream(filePath));
            result = getNameCell(book, nameName);
            book.close();
        }
        return result;
    }

    /**
     * 根据名称得到名称管理器中的名称单元格引用
     *
     * @param book
     * @param nameName
     * @return CellReference
     */
    public static CellReference getNameCell(Workbook book, String nameName) {
        CellReference result = null;
        // 打开Excel文件
        if (book != null) {
            Name name = book.getName(nameName);
            if (name != null) {
                result = new CellReference(name.getRefersToFormula());
            }
        }
        return result;
    }
}

在单元测试代码中通过CellReference来获取单元格。

CellReference中记录着sheet名字,行号,列号。

class PoiExcelUtilTest {
    String excelPath = "E:\\resource\\20230801.xlsx";

    @Test
    void getNameCell()  throws IOException {
        Workbook book = new XSSFWorkbook(new FileInputStream(excelPath));
        CellReference cell = PoiExcelUtil.getNameCell(book, "name1");
        //先找到Sheet
        Sheet sheet = book.getSheet(cell.getSheetName());
        //再找到单元格
        Cell c = sheet.getRow(cell.getRow()).getCell(cell.getCol());
        System.out.println(c.getNumericCellValue());
    }

    @Test
    void listNameCell() throws IOException {
        List<CellReference> cells = PoiExcelUtil.listNameCell(excelPath);
        System.out.println(StrUtil.toString(cells));
    }

    @Test
    void getNameCell2()  throws IOException {
        CellReference cell = PoiExcelUtil.getNameCell(excelPath, "name1");
        System.out.println(StrUtil.toString(cell));
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/837730.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言案例 不重复数字输出--01

题目&#xff1a;有 1、2、3、4 四个数字&#xff0c;能组成多少个互不相同且无重复数字的三位数&#xff1f;都是多少&#xff1f; 步骤一&#xff1a;定义程序目标 编写一个C程序&#xff0c;使用1、2、3、4四个数字组成不相同且不重复的三位数&#xff0c;分别显示出来…

从web漏洞到linux权限提升

从web漏洞到linux权限提升 一、Linux系统介绍与使用二、Linux权限说明2.1、文件权限2.2、linux文件、目录权限说明 三、权限提升 一、Linux系统介绍与使用 linux-全称GNU/Linux&#xff0c;是一种免费使用和自由传播的类UNIX操作系统&#xff0c;是基于POSIXI的多用户、多任务…

关于Monkey稳定性测试,这是我看到最详细的文章

通过随机点击屏幕一段时间&#xff0c;看看app会不会崩溃&#xff0c;能不能维持正常运行&#xff0c;这就是稳定性测试。 01、Monkey是什么 Monkey测试是Android平台自动化测试的一种手段&#xff0c;通过Monkey程序模拟用户触摸屏幕、滑动Trackball、按键等操作来对设备上的…

8.4 作业

1.思维导图 2.判断家目录下&#xff0c;普通文件的个数和目录文件的个数 #!/bin/bash count10 count20 cd ~ for i in $(ls) doif [ -f "$i" ]thencount1$((count11))elif [ -d "$i" ]then count2$((count21))fi done echo $count1 echo $count2 3.输入一…

MySQL数据库免安装版

MySQL数据库免安装 1.安装配置启动 MySQL现在的版本主要分为: 5.x 版本,现在互联网企业中的主流版本,包括:头条、美图、百度、腾讯等互联网公司主流的版本。8.x 版本,新增了一些了窗口函数、持久化配置、隐藏索引等其他功能。所以,我们课程会以常用大版本中最新的版本为…

Camunda BPM Run下载(7.20)

官网地址: https://camunda.com/ 中文站点:http://camunda-cn.shaochenfeng.com https://downloads.camunda.cloud/release/camunda-bpm/run/7.20/https://downloads.camunda.cloud/release/camunda-bpm/run/7.20/camunda-bpm-run-7.20.0-alpha3.ziphttps://downloads.camunda…

科技云报道:震惊!4K、8K画质背后,竟然少不了AI的助力

科技云报道原创。 “对于视频的画质&#xff0c;我现在最低只能够接受720P&#xff0c;最好是1080p。”早五年前&#xff0c;身边就已经有人提出了这样的要求。 随着科技的进步&#xff0c;我们进入了一个视频内容快速增长的时代。从社交媒体到在线教育&#xff0c;从直播购物…

JS解析JSON

在 JavaScript 中解析 JSON 数据 在 JavaScript 中&#xff0c;您可以使用 JSON.parse() 方法来解析 JSON 数据&#xff0c;示例代码如下&#xff1a; var json {"course": {"name": "JavaScript","author": "http://c.bianch…

拉普拉斯平滑算法

原理 最简单的拉普拉斯平滑算法的原理是将每个顶点都移动到相邻顶点的平均位置上。公式 示例&#xff08;UE5代码片段&#xff09; 参考 https://blog.csdn.net/mrbaolong/article/details/105859109

MyBatis-动态SQL-if and where

动态SQL 随着用户的输入或外部条件的变化而变化的SQL语句&#xff0c;我们称之为动态SQL语句 select *from empwhere name like concat(%, #{name}, %)and gender #{gender}and entrydate between #{begin} and #{end}order by update_time desc; 在上述的SQL语句…

运输层---概述

目录 运输层主要内容一.概述和传输层服务1.1 概述1.2 传输服务和协议1.3 传输层 vs. 网络层1.4 Internet传输层协议 二. 多路复用与多路分解&#xff08;解复用&#xff09;2.1 概述2.2 无连接与面向连接的多路分解&#xff08;解复用&#xff09;2.3面向连接的多路复用*2.4 We…

⌈C++⌋从无到有了解并掌握C++面向对象三大特性——封装、继承、多态

前置知识&#xff1a;类和对象 参考书籍&#xff1a;《C Primer 第五版》 目录 什么是面向过程&#xff1f;什么是面向对象&#xff1f; 一、封装 1、封装的含义以及如何实现封装 1.1 访问限定符&#xff08;访问说明符&#xff09; 1.2 什么是封装&#xff1f; 2、封装的优点…

MySQL~mysql基础应用相关题

整卷阅览&#xff1a; 想要获取试卷原版请点击以下链接下载&#xff1a; https://download.csdn.net/download/qq_53142796/88168133https://download.csdn.net/download/qq_53142796/88168133 解题过程&#xff1a; 数据库&#xff1a;studentdb 数据库表如下&#xff1a; …

数学建模-元胞自动机

clc clear n 300; % 定义表示森林的矩阵大小 Plight 5e-6; Pgrowth 1e-2; % 定义闪电和生长的概率 UL [n,1:n-1]; DR [2:n,1]; % 定义上左&#xff0c;下右邻居 vegzeros(n,n); % 初始化表示森林的矩阵 imh ima…

01-序言

文章作者&#xff1a;里海 来源网站&#xff1a;https://blog.csdn.net/WangPaiFeiXingYuan 简介&#xff1a; 此专栏是学习“线性代数”课程做的笔记&#xff0c;教程来自B站的3Blue1Brown​​​​​​​d​​​​​​​。 视频作者是Grant Sanderson&#xff0c; 他本人是斯坦…

【蓝图】p48冲刺、瞬移、多段跳

p48冲刺&#xff0c;瞬移&#xff0c;多段跳 p48冲刺&#xff0c;瞬移&#xff0c;多段跳冲刺功能实现瞬移功能实现Set Actor Location&#xff08;设置Actor位置&#xff09; 二段跳 p48冲刺&#xff0c;瞬移&#xff0c;多段跳 按shift加速&#xff0c;松开shift恢复普通速度…

echarts-pie---------3D曲状环形饼图实现!!!

示例&#xff08;参考此处饼图修改https://www.isqqw.com/viewer?id37497&#xff09; 话不多说直接上代码 此套代码可以直接再echarts官网中的此处运行 let selectedIndex ; let hoveredIndex ; option getPie3D([{name: 数学,value: 60,itemStyle: {color: #1890FF,},},{…

Vue2 第二十节 vue-router (一)

1.相关概念理解 2.基本路由 3.嵌套路由&#xff08;多级路由&#xff09; 一.相关概念理解 1.1 vue-router的理解 路由&#xff1a;就是一组key-value的对应关系, key为路径&#xff0c;value可能是function或者component多个路由&#xff0c;需要经过路由器的管理编程中的…

【树状数组】讲解

一.介绍 树状数组&#xff08;Fenwick Tree&#xff09;&#xff0c;也称为二叉索引树&#xff08;Binary Indexed Tree&#xff0c;BIT&#xff09;&#xff0c;是一种用于高效处理动态数组前缀和的数据结构。它可以在O(log n)的时间复杂度内完成单点更新和区间查询操作。 树…

【Python】模块学习之locust性能测试

目录 背景 安装 测试代码 运行命令 资料获取方法 背景 locust是一个python的第三方库&#xff0c;用于做性能测试&#xff0c;可使用多台机器同时对一台服务器进行压测&#xff0c;使用其中一台机器作为主节点&#xff0c;进行分布式管理 博主测试接口的时候一直是使用p…