2017-09-02 22 views
1

我有打印所有excel單元格值的代碼,但它忽略了空白單元格。有沒有辦法打印空白單元格的值(空)?使用java從Excel中打印10和11列的值

還可以打印特定的2列(空白單元格)像第10和第11列?

以下是我的代碼。請建議我可以在下面的代碼中更改什麼?

package excel; 

import java.io.File; 
import java.io.FileInputStream; 
import java.util.Iterator; 

import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class Excel 
{ 
    public static void main(String[] args) { 
     try { 
      FileInputStream file = new FileInputStream(new File("C:\\Users\\gur29175\\Desktop\\1.xlsx")); 

      //Create Workbook instance holding reference to .xlsx file 
      XSSFWorkbook workbook = new XSSFWorkbook(file);   
      XSSFSheet sheet = workbook.getSheetAt(0); 

      //Iterate through each rows one by one 
      Iterator<Row> rowIterator = sheet.iterator(); 
      while (rowIterator.hasNext()) 
      { 
       Row row = rowIterator.next(); 
       //For each row, iterate through all the columns 
       Iterator<Cell> cellIterator = row.cellIterator(); 

       while (cellIterator.hasNext()) 
       { 
        Cell cell = cellIterator.next(); 
        //Check the cell type and format accordingly 
          System.out.print(cell.getStringCellValue() + "\t"); 


       } 
       System.out.println(""); 
      } 
      file.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

https://poi.apache.org/spreadsheet/quick-guide.html#Iterate+over+cells%2C+with+control+of+missing+%2F+blank+cells –

回答

1
Row row = rowIterator.next(); 
for(int i = 0; i < row.getLastCellNum(); i++) { 
    Cell cell = row.getCell(i); 
    if(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { 
     // handle not null values 
    }else{ 
     // handle null values 
    } 
}