2011-06-03 40 views
1

我使用Apache POI-HSSF處理Excel文件。Apache POI-HSSF:取得小數而不是文本字符串

我的電子表格中有一個單元格,看起來像「115」。我確認它被格式化爲「文本」(格式化單元格 - >文本)。

然而,當我在讀它作爲 row.getCell(0)的ToString()

我得到這個字符串: 「115.0」

這是不正確。因爲它被明確地格式化爲文本,所以我應該得到「115」。我怎樣才能得到想要的結果?單元格可以是任何東西,數字或字符,我希望與單元格中的字符串相同。謝謝

回答

2

格式化爲文本並不意味着存儲爲文本,它們是不同的。 Excel已將您的單元存儲爲一個數字,並且當您向該單元詢問POI時,會返回一個數字單元格。

如果你問你回來它是什麼類型的細胞,你會發現它的類型CELL_TYPE_NUMERIC,而不是CELL_TYPE_STRING

你可能會想要做的是使用DataFormatter class有你的格式爲每個Excel。它會看起來像你期望的。 (如將單元格格式化爲貨幣,百分比等)

+0

謝謝,它的工作 – user783312 2011-06-10 23:40:17

1

您應該調用HSSFCell.getCellType()方法來確定其類型。這裏有一個處理String或Numeric類型的單元格的方法。 (您可以輕鬆添加其他類型。)用於數字的格式將是有效的格式,但不一定與SpreadSheet的格式相匹配。 (如下所示。)

public static String getCellStringValue(final HSSFCell cell) { 
    int cellType = cell.getCellType(); 
    String value; 
    if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { 
     // Locale is optional here 
     DataFormatter dataFormatter = new DataFormatter(Locale.US); 
     value = dataFormatter.formatCellValue(cell); 
    } else { 
     // HSSFCell.CELL_TYPE_STRING 
     value = cell.getStringCellValue(); 
    } // more cell types are possible. Add whatever you need. 
    return value; 
} 

該代碼不一定會格式化數字,因爲它出現在Excel中。 如果您需要的格式與電子表格格式完全匹配,則可以從單元格本身獲取格式化程序。要做到這一點,你可以使用你的DataFormatter實例來創建一個Format實例:

public static String getCellStringValue(final HSSFCell cell) { 
    int cellType = cell.getCellType(); 
    String value; 
    if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { 
     // Locale is optional here 
     DataFormatter dataFormatter = new DataFormatter(Locale.US); 
     Format format = dataFormatter.createFormat(cell); 
     value = format.format(cell.getNumericCellValue()); 
    } else { 
     // HSSFCell.CELL_TYPE_STRING 
     value = cell.getStringCellValue(); 
    } // more cell types are possible. Add whatever you need. 
    return value; 
} 
相關問題