简体   繁体   English

界面工作簿、工作表和行与 Classess XSSFWorkbook、XSSFSheet 的混淆

[英]Confusion on Interface Workbook, Sheet and Row vs Classess XSSFWorkbook, XSSFSheet

Below is a simple code to access all the cells of an excel sheet.下面是访问 excel 表的所有单元格的简单代码。 I didn't use the classes XSSFWorkbook, XSSFSheet...etc My confusion is if an interface only holds signature of the methods then how come I'm able to use methods like getRow, getCell using interfaces?我没有使用 XSSFWorkbook、XSSFSheet 等类。我的困惑是,如果接口只包含方法的签名,那么我为什么能够使用 getRow、getCell 等方法呢?

(where are those methods defined that are listed when I type sheet and then type period) (当我键入 sheet 然后键入句点时列出的那些定义的方法在哪里)

Thanks in advance.提前致谢。

 FileInputStream inputStream = new FileInputStream("C:\\Eclipse\\WorkSpace\\YPractice\\TestCase.xlsx");
    
    Workbook guru99Workbook = null;     
    
    guru99Workbook = new XSSFWorkbook(inputStream);                                 
    Sheet sheet = guru99Workbook.getSheet("KeywordFramework");
    
    int RowNum = sheet.getLastRowNum() - sheet.getFirstRowNum();
    

    for (int i = 0; i<=RowNum; i++)
    {

        Row row = sheet.getRow(i);
    
        
        for(int j= 0; j<row.getLastCellNum(); j++)
        {
            System.out.println("Data = " +i + " " +row.getCell(j));
            
        }
    }

You are using the XSSFWorkbook implementation of Workbook when you do:当您执行以下操作时,您正在使用WorkbookXSSFWorkbook实现:

guru99Workbook = new XSSFWorkbook(inputStream);

Later you use getSheet() on guru99Workbook .稍后您在guru99Workbook上使用getSheet() Given that guru99Workbook is an XSSFWorkbook , you'll get in return a XSSFSheet .鉴于guru99WorkbookXSSFWorkbook ,您将获得XSSFSheet的回报。

This is similar to:这类似于:

List<String> list = new ArrayList<>();

To answer your second question, the methods are listed in:为了回答您的第二个问题,方法列在:

  1. XSSFWorkbook : getSheet(String name) XSSFWorkbookgetSheet(String name)
  2. XSSFSheet : getRow(int rownum) , getFirstRowNum() , getLastRowNum() XSSFSheetgetRow(int rownum)getFirstRowNum()getLastRowNum()
  3. XSSFRow : getLastCellNum() getCell(int cellnum) XSSFRow : getLastCellNum() getCell(int cellnum)

The getRow(int) method is defined in the Sheet interface , and that's why you can call it from your Sheet sheet variable. getRow(int)方法是在Sheet interface中定义的,这就是为什么您可以从Sheet工作sheet变量中调用它的原因。 Likewise, getCell(int) is defined in the Row interface, and thus, can be accessed through your Row typed row variable.同样, getCell(int)Row接口中定义,因此可以通过Row类型的row变量访问。

Your intuition about how interfaces work in Java is perfectly correct.您对 Java 中接口如何工作的直觉是完全正确的。 You may have misread the Sheet and Row interfaces' documentation.您可能误读了SheetRow接口的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM