当前位置: 首页 > 知识库问答 >
问题:

在我的应用程序中没有得到正确的行号或值。(Apache poi)

梁存
2023-03-14

这是我的代码:

public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        // c => cell
        System.out.println("The Value of Row is : "+attributes.getValue("r"));
        if(name.equals("c")) {
            // Print the cell reference
            // Figure out if the value is an index in the SST
            String cellType = attributes.getValue("t");
            if(cellType != null && cellType.equals("s")) {
                nextIsString = true;
            } else {
                nextIsString = false;
            }
        }

当我使用bellow line打印行号时,我得到的是bellow输出。

System.out.println("The Value of Row is : "+attributes.getValue("r"));

输出为:

The Value of Row is : null The Value of Row is : 1 The Value of Row is : A1 The Value of Row is : null The Value of Row is : B1 The Value of Row is : null The Value of Row is : C1 The Value of Row is : null The Value of Row is : D1
The Value of Row is : null
The Value of Row is : E1
The Value of Row is : null
The Value of Row is : F1
The Value of Row is : null
The Value of Row is : G1
The Value of Row is : null
The Value of Row is : H1
The Value of Row is : null
The Value of Row is : I1
The Value of Row is : null
The Value of Row is : J1
The Value of Row is : null
The Value of Row is : AMD1
The Value of Row is : AME1
The Value of Row is : AMF1
The Value of Row is : AMG1
The Value of Row is : AMH1
The Value of Row is : AMI1
The Value of Row is : AMJ1
The Value of Row is : 2
The Value of Row is : A2
The Value of Row is : null
The Value of Row is : B2
The Value of Row is : null
The Value of Row is : C2
The Value of Row is : null
The Value of Row is : D2

我怎样才能只得到行号?1,2,3,4,5,6,.....像那样?

而且

我如何获得列的总数和行的数量?

共有1个答案

朱毅
2023-03-14

如注释中所述,这不是使用apache POI读取Excel工作表的默认方式。请阅读https://poi.apache.org/spreadsheet/quick-guide.html。特别是https://poi.apache.org/spreadsheet/quick-guide.html#迭代器

对于您的sax.ContentHandler代码:

Excel工作表的XML如下所示:

...
<sheetData>
 <row r="1">
  <c r="A1">
   <v>1</v> 
  </c>
  <c r="B1">
   <v>2</v> 
  </c>
 </row>
...

正如您所看到的,有不同的元素,不仅仅是行,“r”属性在这些元素中有不同的含义。在元素“v”中为空。

因此必须首先检查是否有行元素:

...
if(name.equals("row")) { 
   System.out.println("The Value of Row is : "+attributes.getValue("r"));
 }

但是,如上所述,我不知道这是否真的是对你最好的方式。

public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        // c => cell
        if(name.equals("row")) {
             System.out.println("The Value of Row is : "+attributes.getValue("r"));
        }
...
 类似资料: