2013-08-28 60 views
25

Tôi muốn số cột của một hàng cụ thể trong excel. Làm thế nào là có thể? Tôi đã sử dụng POI APIlấy số cột của một hàng cụ thể trong excel đã cho bằng cách sử dụng Java

nhưng tôi chỉ có thể nhận được các cột được tính là 7.

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); 

} 

Tôi muốn số lượng cột ở một số hàng cụ thể là 10. cột Các excel không giống nhau

Trả lời

44

Có hai điều bạn có thể làm

sử dụng

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

hoặc

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

Có một sự khác biệt tinh tế giữa họ

  1. O ption 1 cho phép không có cột nào chứa đầy nội dung (Nếu cột thứ 2 của 10 cột không được điền, bạn sẽ nhận được 9)
  2. Phương án 2 chỉ cho bạn chỉ mục cột cuối cùng. Do đó thực hiện 'getLastCellNum()'
+2

Theo [ 'getLastCellNum()'] (http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html #getLastCellNum()), một cái đã được thêm vào, vì vậy bạn không thể tự thêm một mình. – rgettman

+0

Đã chỉnh sửa với các thay đổi. Cảm ơn bạn đã chỉ ra điều tương tự. –

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; 
} 
Các vấn đề liên quan