2013-08-28 11 views
25

Voglio il numero di colonne di una particolare riga in Excel. Come è possibile? Ho usato l'API POIottiene il numero di colonne di una particolare riga in excel dato utilizzando Java

ma ho potuto contare solo su 7 colonne.

try 
      { 
       fileInputStream = new FileInputStream(file); 
       workbook = new HSSFWorkbook(fileInputStream); 
       Sheet sheet = workbook.getSheet("0"); 


       int numberOfCells = 0; 
       Iterator rowIterator = sheet.rowIterator(); 
       /** 
       * Escape the header row * 
       */ 
       if (rowIterator.hasNext()) 
       { 
        Row headerRow = (Row) rowIterator.next(); 
        //get the number of cells in the header row 
        numberOfCells = headerRow.getPhysicalNumberOfCells(); 
       } 
       System.out.println("number of cells "+numberOfCells); 

} 

Voglio il numero di colonne di un numero di riga particolare dire 10. colonne di Excel non sono gli stessi

risposta

44

Ci sono due cose che puoi fare

uso

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells(); 

o

int noOfColumns = sh.getRow(0).getLastCellNum(); 

C'è una bella differenza tra loro

  1. O ption 1 dà il numero di colonne che sono effettivamente piene di contenuti (Se la seconda colonna di 10 colonne non è riempita, si otterrà 9)
  2. L'opzione 2 ti dà solo l'indice dell'ultima colonna. Da qui fatto 'getLastCellNum()'
+2

Secondo [ 'getLastCellNum()'] (http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html #getLastCellNum()), ne è già stato aggiunto uno, quindi non devi_ne aggiungere uno tu stesso. – rgettman

+0

Modificato con modifiche. Grazie per aver fatto notare lo stesso. –

0
/** Count max number of nonempty cells in sheet rows */ 
private int getColumnsCount(XSSFSheet xssfSheet) { 
    int result = 0; 
    Iterator<Row> rowIterator = xssfSheet.iterator(); 
    while (rowIterator.hasNext()) { 
     Row row = rowIterator.next(); 
     List<Cell> cells = new ArrayList<>(); 
     Iterator<Cell> cellIterator = row.cellIterator(); 
     while (cellIterator.hasNext()) { 
      cells.add(cellIterator.next()); 
     } 
     for (int i = cells.size(); i >= 0; i--) { 
      Cell cell = cells.get(i-1); 
      if (cell.toString().trim().isEmpty()) { 
       cells.remove(i-1); 
      } else { 
       result = cells.size() > result ? cells.size() : result; 
       break; 
      } 
     } 
    } 
    return result; 
} 
Problemi correlati