2014-03-06 72 views
2

我的目標是讀取一個使用POI的excel文件並打印其中存在的值。如果值是5,那麼我的輸出必須是5,但它返回爲5.0。以下是我嘗試過的代碼。使用JAVA從excel中檢索INTEGER值

FileInputStream fileInputStream = null; 
    XSSFSheet xssfResultSheet = null; 
    String filePath = "C:\\MyXcel.xlsx"; 
    fileInputStream = new FileInputStream(new File(filePath)); 
    XSSFWorkbook workbook = null; 
    workbook = new XSSFWorkbook(fileInputStream); 
    xssfResultSheet = workbook.getSheet("Sheet1"); 
    int iRowCount = xssfResultSheet.getLastRowNum(); 

    for (int i = 1; i <= iRowCount; i++) { 
     Row resultRow = xssfResultSheet.getRow(i); 
     System.out.println(resultRow.getCell(0)); 
    } 

我的Excel的值是1,2,3,但我的輸出是1.0,2.0,3.0。相反,我的輸出也應該是1,2,3

+0

據我所知,getCell總是返回浮點值。你有沒有嘗試解析爲整數,然後對數值做Math.round()? –

+1

Excel中的所有數值都是(64位)加倍。 –

回答

6

變化:

System.out.println(resultRow.getCell(0)); 

要:

System.out.println(new DataFormatter().formatCellValue(resultRow.getCell(0))); 

說明:

apache-poiDataFormatter類作爲實用工具來利用內容的格式,因爲它在excel上顯示爲。您可以選擇自定義格式也一樣,一個簡單的例子是(細胞是參考你的XSSFCell對象):

Excel工作表的樣子:

enter image description here

代碼:

System.out.println(new DataFormatter().formatCellValue(cell)); 

以上行可打印:

50% 
$ 1,200 
12/21/14 
9886605446 

而正常的打印將有不同的解釋是:

0.5 
1200.0 
21-Dec-2014 
9.886605446E9 
+0

感謝您的解釋。工作正常。 – user3387609

1

POI應該有一個cell.getRawValueAsString()方法,但AFAIK不是這種情況。您在Excel中看到的顯示文本是值+格式的總和。所以,如果你想恢復它「爲顯示」:

  • 檢索單元對象
  • 單元格的值使用相關CellStyle檢索單元格的格式。
  • 申請格式使用DataFormatter
  • 重視
+0

雖然Apache POI確實有這種方法!它是[DataFormatter.formatCellValue(Cell)](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DataFormatter.html#formatCellValue%28org.apache.poi.ss.usermodel.Cell% 29) – Gagravarr

-2

的Apache POI解釋你的numerial細胞值加倍,爲了避免這種情況,嘗試設置的細胞類型。也許這將幫助你:

for (int i = 1; i <= iRowCount; i++) { Row resultRow = xssfResultSheet.getRow(i); resultRow.getCell(i).setCellType(Cell.CELL_TYPE_STRING); System.out.println(Integer.parseInt(resultRow.getCell(0).toString())); }

+0

如果您查看[Apache POI Javadocs for setCellType](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29),它們是非常明確,這是*不正確的做法! – Gagravarr

+0

是的,這不是正確的方式,但是是一種方式;)一個簡單易用的方法。讓它工作,然後讓它清潔;) –

0

試試這個,

System.out.println((int)Math.round(cell.getNumericCellValue()));