2017-04-18 182 views
0

我在我的應用程序中使用Apache poi庫的代碼,但問題是他正在讀取我不想要的單元格。正因爲如此,我想現在如何從第33行開始讀取單元格。我該怎麼做?如何在android中使用Apache poi讀取excel文件時跳過單元格?

File file = new File(inFileName); 
      Workbook workBook = WorkbookFactory.create(file); 
      Sheet sheet = workBook.getSheetAt(0); 


      Iterator<Row> rowIter = sheet.rowIterator(); 
      while(rowIter.hasNext()){ 

       Row myRow =rowIter.next(); 


       Cell cell1 = myRow.getCell(0); 
       Cell cell2 = myRow.getCell(1); 
       ... 


       Iterator<Cell> cellIter = myRow.cellIterator(); 
       while(cellIter.hasNext()){ 
        Cell myCell = cellIter.next(); 

       } 

       //bd.addAnimalls(cell1.toString(),cell2.toString()); 

       Toast.makeText(getApplicationContext(), "on inserting", Toast.LENGTH_SHORT).show(); 



      } 

回答

0

您可確定物理行的總數與sheet.getPhysicalNymberOfRows(),並以此作爲上索引限制。 然後,代替sheet.rowIterator(),使用基於索引的行sheet.createRow(index)

for (int i = 33; i < sheet.getPhysicalNymberOfRows(); i ++) 
{ 
    Row r = sheet.createRow(i); 
    .... 
} 
+0

我需要另一種方式。也許一個if語句在while循環中? – jose

+0

你可以把它放在任何你需要的地方)我展示了一個基本概念,如何從指定的行索引 –

+0

開始讀取,但索引是什麼? – jose

0

這是覆蓋在the Apache POI documentation on iterating over rows and cells。閱讀文檔非常值得!

從Excel列33起,這是POI列32(POI行是基於0),最多1400行(作爲一個例子)迭代,你會想要做的事,如:

int rowStart = 33-1; // POI rows are 0 based 
int rowEnd = Math.min(1400, sheet.getLastRowNum()); 
final int MY_MINIMUM_COLUMN_COUNT = 10; // Minimum number of columns to consider 

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { 
    Row r = sheet.getRow(rowNum); 
    if (r == null) { 
     // This whole row is empty 
     // Handle it as needed 
     continue; 
    } 

    int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT); 

    for (int cn = 0; cn < lastColumn; cn++) { 
     Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL); 
     if (c == null) { 
     // The spreadsheet is empty in this cell 
     } else { 
     // Do something useful with the cell's contents 
     } 
    } 
} 
相關問題