首页 \ 问答 \ 使用Apache POI及其名称获取Excel公式的内容(Get Content of a Excel Formula with Apache POI and its name)

使用Apache POI及其名称获取Excel公式的内容(Get Content of a Excel Formula with Apache POI and its name)

问题是如何通过名称获取公式的内容。 在Excel中,您可以使用公式名称对表进行分组。 我想用Apache POI获取这样一个名为table的公式的内容。 因此,即使表格得到扩展,我也始终获得最新数据。 由于名称没有改变。

我做了一些编码,但到目前为止,我只能获得一张纸的所有内容,而不仅仅是一张带有公式名称的表。 我的代码在下面,谢谢。

package getTablesPOI;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;


public class readExcel {

    // Creates a new instance of POIExcelReader
    public readExcel() {
    }

    /**
     * The main executable method to test readExcel method.
     *
     * @param args
     */

    public static void main(String[] args) throws InvalidFormatException {
        readExcel excelStuff = new readExcel();
        String cisFile = "C://Users//agoebbel//Desktop//PS//# Downloads - Files//POI_Test.xlsx";
        String sheetName = "Main";
        String searcher = "Something";

        excelStuff.displayFromExcel(cisFile, sheetName, searcher);
    }


    /**
     * This method is used to display the Excel content to command line.
     *
     * @param cisFile
     * @param sheetName
     * @param searcher
     */
    public void displayFromExcel(String cisFile, String sheetName, String searcher) throws InvalidFormatException {
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(cisFile);
        } catch (FileNotFoundException e) {
            System.out.println("File not found in the specified path.");
            e.printStackTrace();
        }

        try {
            OPCPackage opc = OPCPackage.open(inputStream);
            Workbook workbook;
            workbook = WorkbookFactory.create(opc);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet(sheetName);
            Iterator<Row> rows = sheet.rowIterator();
            // String searcher = (new CellReference((Cell) rows)).formatAsString();

            while (rows.hasNext()) {
                XSSFRow row = (XSSFRow) rows.next();

                // display row number in the console.
                System.out.println("\n" + "Row No.: " + new Integer(row.getRowNum() + 1));

                // once get a row its time to iterate through cells.
                Iterator<Cell> cells = row.cellIterator();

                while (cells.hasNext()) {
                    Cell cell = cells.next();


                    // Now we will get the cell type and display the values accordingly.
                    switch (cell.getCellType())  //cell.getCellType ()
                    {
                        case Cell.CELL_TYPE_FORMULA: {
                            cell.getCellFormula();
                            switch (cell.getCachedFormulaResultType()) {

                                case Cell.CELL_TYPE_NUMERIC:
                                    System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                                    break;
                            }

                        }

                        case Cell.CELL_TYPE_NUMERIC: {

                            // cell type numeric.
                            System.out.println(cell.getNumericCellValue());

                            break;
                        }

                        case Cell.CELL_TYPE_STRING: {

                            // cell type string.
                            System.out.println(cell.getStringCellValue());

                            break;
                        }

                        default: {

                            // types other than String and Numeric.
                            System.out.println("Type not known.");

                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Question is how I can get the content of a formula by name. In Excel you can group Tables with a formula name. I want to get the content of such a formula named table with Apache POI. So that I always get up-to-date data even if the table get extended. Since the name does not change then.

I did some coding but so far I only archieved to get all contents of a sheet and not just of a table with formula name. My code is below, thanks.

package getTablesPOI;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;


public class readExcel {

    // Creates a new instance of POIExcelReader
    public readExcel() {
    }

    /**
     * The main executable method to test readExcel method.
     *
     * @param args
     */

    public static void main(String[] args) throws InvalidFormatException {
        readExcel excelStuff = new readExcel();
        String cisFile = "C://Users//agoebbel//Desktop//PS//# Downloads - Files//POI_Test.xlsx";
        String sheetName = "Main";
        String searcher = "Something";

        excelStuff.displayFromExcel(cisFile, sheetName, searcher);
    }


    /**
     * This method is used to display the Excel content to command line.
     *
     * @param cisFile
     * @param sheetName
     * @param searcher
     */
    public void displayFromExcel(String cisFile, String sheetName, String searcher) throws InvalidFormatException {
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(cisFile);
        } catch (FileNotFoundException e) {
            System.out.println("File not found in the specified path.");
            e.printStackTrace();
        }

        try {
            OPCPackage opc = OPCPackage.open(inputStream);
            Workbook workbook;
            workbook = WorkbookFactory.create(opc);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheet(sheetName);
            Iterator<Row> rows = sheet.rowIterator();
            // String searcher = (new CellReference((Cell) rows)).formatAsString();

            while (rows.hasNext()) {
                XSSFRow row = (XSSFRow) rows.next();

                // display row number in the console.
                System.out.println("\n" + "Row No.: " + new Integer(row.getRowNum() + 1));

                // once get a row its time to iterate through cells.
                Iterator<Cell> cells = row.cellIterator();

                while (cells.hasNext()) {
                    Cell cell = cells.next();


                    // Now we will get the cell type and display the values accordingly.
                    switch (cell.getCellType())  //cell.getCellType ()
                    {
                        case Cell.CELL_TYPE_FORMULA: {
                            cell.getCellFormula();
                            switch (cell.getCachedFormulaResultType()) {

                                case Cell.CELL_TYPE_NUMERIC:
                                    System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                                    break;
                            }

                        }

                        case Cell.CELL_TYPE_NUMERIC: {

                            // cell type numeric.
                            System.out.println(cell.getNumericCellValue());

                            break;
                        }

                        case Cell.CELL_TYPE_STRING: {

                            // cell type string.
                            System.out.println(cell.getStringCellValue());

                            break;
                        }

                        default: {

                            // types other than String and Numeric.
                            System.out.println("Type not known.");

                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

原文:https://stackoverflow.com/questions/36030143
更新时间:2022-10-21 07:10

最满意答案

这听起来正确。

业务层边界技术中立的方式实现域模型 。 换句话说,它不依赖于任何特定的UI或服务接口相关技术,如Web库或窗口API。 您应该能够从任何类型的应用程序 - 网络,富客户端,Web服务等消费业务层。

应用层弥合了业务层和边界技术之间的差距。


That sounds about correct.

The business layer implements the Domain Model in a boundary-technology-neutral way. In other words, it doesn't depend on any particular UI or service interface-related technology, such as web libraries or windowing APIs. You should be able to consume the business layer from any type of application - web, rich client, web service, etc.

The application layer bridges the gap between the business layer and the boundary technology.

相关问答

更多
  • 这听起来正确。 业务层以边界技术中立的方式实现域模型 。 换句话说,它不依赖于任何特定的UI或服务接口相关技术,如Web库或窗口API。 您应该能够从任何类型的应用程序 - 网络,富客户端,Web服务等消费业务层。 应用层弥合了业务层和边界技术之间的差距。 That sounds about correct. The business layer implements the Domain Model in a boundary-technology-neutral way. In other words, ...
  • 我这样做的方式 - 我不是说这是对是错的,是让我的视图,然后一个适用于我的观点的模型。 这个模型只有与我的观点有关 - 包括数据注释和验证规则。 控制器只提供构建模型的逻辑。 我有一个包含所有业务逻辑的服务层。 我的控制器调用我的服务层。 除此之外,我的存储库层。 我的域对象分开安装(实际上在自己的项目中)。 他们有自己的数据注释和验证规则。 我的存储库会将我们的域中的对象保存到数据库中。 因为我的域中的每个对象都继承自内置验证的基类,我的存储库是通用的,并验证所有的东西(并要求它从基类继承)。 你可能认为 ...
  • 将足够的业务逻辑放在数据库中,以确保数据一致和正确。 但不要害怕在另一个级别复制这些逻辑,以增强用户体验。 Put enough of the business logic in the database to ensure that the data is consistent and correct. But don't fear having to duplicate some of this logic at another level to enhance the user experience. ...
  • 是的我同意视图模型中没有业务逻辑,除非它是非常简单的数学计算。 我工作的公司喜欢将所有业务逻辑保留在模型中。 我个人认为你的项目中应该有一个服务层来处理所有这些逻辑。 但是,视图模型应该集中在视图,获取和发送输入,最好通过INotifyPropertyChanged接口更新值/属性。 我喜欢将视图模型视为指导交通的学校的“交叉卫士”。 :P - 希望这会有所帮助 Yes I agree with not having business logic in the view model unless it's ...
  • 您可以使用洋葱架构,也称为六角形或端口和适配器(对同一事物略有不同的变化)。 使用此体系结构,您的持久性(数据)层引用您的域层,因此您的存储库等可以返回域实体。 为了从域层使用您的存储库,您需要将存储库的接口放在域层中,并使用IoC容器将它们连接到实现(在持久层中)。 编辑 听起来好像你从你的术语和你提供的代码示例中做DDD,我猜你因为术语库而包含了DDD标签,所以我将继续使用非DDD, n层和分层术语。 你会看到一个几乎相同的调用栈。 它将是Controller - > Service - > Repos ...
  • 使用分层架构时,一定不要教条。 您可以测量任何功能的抽象。 这项措施很灵活。 在您的具体示例中,您正在考虑验证实体的字符串大小。 现在,名称实体将它放在数据层附近,这是我放置的位置。 因此,如果有人试图放置长度错误的实体,您的数据层可能会引发访问冲突。 You must not be dogmatic when using layered architecture. You may measure some abstraction to any piece of function. This measure ...
  • 如果您的业务逻辑仍然在SQL语句中,那么数据库将执行与以前一样多的工作,并且您将无法获得更好的性能。 (如果无法像使用存储过程那样有效地缓存查询计划,可能会更有效) 要获得更好的性能,您需要将一些工作移到应用程序层,例如,您可以在应用程序服务器上缓存数据,并在不访问数据库的情况下执行查找或验证检查吗? If your business logic is still in SQL statements, the database will be doing as much work as before, an ...
  • 如果业务逻辑层需要知道用户是否已登录,则应将该信息作为参数传递。 业务层不应该知道用户是如何进行身份验证的,如果需要知道用户是否已登录,则应该获得该信息 - 这是对您的关注点分离! :) 主要思想是,即使在完全不同的环境中,您也可以始终重用相同的业务规则,例如,使用不同的身份验证机制。 If the business logic layer needs to know if the user is logged in, you should just pass along that information ...
  • Java EE提倡贫血模型,这与DDD相反。 如果您想要DDD,您的实体也必须执行业务逻辑,这与服务层和实体的分离相反。 Java EE advocates anemic model, which is the opposite of DDD. If you want DDD, your entities must also perform the business logic, which is contrary to the separation of service layer and entitie ...
  • 我同意crunchdog--除了最琐碎的Web应用程序之外,您应该为您的UI /视图层专门制作业务对象的扁平形式。 有时候这被称为View Model类,通常只包含几个字符串属性,UI层可以直接从中获取并放入,而不用担心验证。 (请参阅asp.net mvc ) 首先,这使得UI层更加简洁和清晰,让它能够显示数据而不是遍历对象结构,检查和解释空值等。 这也为业务层提供了对这些字符串值进行验证的机会,如果它们无效,则返回输入的值。 例如,当您的服务器必须处理日期字段中的无效日期时,这可以节省编码沮丧。 识别无 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。