Java获取Excel表单控件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java获取Excel表单控件

E-iceblue   2022-06-02 我要评论

Excel中可通过【开发工具】菜单栏下插入表单控件,如文本框、单选按钮、复选框、组合框等等,插入后的控件可执行设置控件格式,如大小、是否锁定、位置、可选文字、数据源区域、单元格链接等。当Excel中已插入上述控件,需要读取时,也可以使用本文中的方法来读取。下面,将通过Java代码示例展示如何来获取Excel文档中的表单控件。以下是读取的方法及步骤,供参考。

引入jar包

按照如下方法来引用Spire.Xls.jar 版本:5.1.0

方法1

将 Free Spire.XLS for Java 包 下载 到本地,解压,找到lib文件夹下的Spire.Xls.jar文件。然后在IDEA中打开“Project Structure”界面,然后执行如图步骤来手动导入本地路径下的jar文件:

方法2:通过 Maven仓库 下载导入,如下配置pom.xml:

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

代码示例

Java

import com.spire.xls.*;
import com.spire.xls.core.ICheckBox;
import com.spire.xls.core.IRadioButton;
import com.spire.xls.core.ISpinnerShape;

public class GetFormControl {
    public static void main(String[] args) {
        //创建Workbook类的实例,加载Excel文档
        Workbook wb = new Workbook();
        wb.loadFromFile("AddControls.xlsx");

        //获取第1张工作表
        Worksheet sheet = wb.getWorksheets().get(0);

        //获取TextBox
        String textbox =  sheet.getTextBoxes().get(0).getText();
        System.out.println(textbox);

        //获取Radio Button
        for(int i = 0; i<sheet.getRadioButtons().getCount();i++)
        {
            IRadioButton radioButton = sheet.getRadioButtons().get(i);
            String name = radioButton.getCheckState().name();
            String text = radioButton.getText();
            boolean islocked = radioButton.isLocked();
            System.out.println(name + text + " 是否锁定:"+ islocked);
        }

        //获取Combo Box控件中的选中的值(注:非列表中所有选项值)
        String value =  sheet.getComboBoxes().get(0).getSelectedValue();
        System.out.println(value);

        //获取Checkbox
        for(int z = 0;z< sheet.getCheckBoxes().getCount();z++)
        {
            ICheckBox checkBox = sheet.getCheckBoxes().get(z);
            String text = checkBox.getText();
            String name = checkBox.getCheckState().name();
            String alternativetext = checkBox.getAlternativeText();
            System.out.println(text + name + alternativetext);
        }

        //获取SpinnerShape
        for(int j  = 0;j<sheet.getSpinnerShapes().getCount();j++)
        {
            ISpinnerShape spinnerShape = sheet.getSpinnerShapes().get(j);
            String rangeAddress = spinnerShape.getLinkedCell().getRangeAddress();
            int currentValue = spinnerShape.getCurrentValue();
            System.out.println(rangeAddress + "\n" + currentValue);
        }

    }
}

获取效果如图所示:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们