我意識到這個問題有點令人困惑,但我不知道該怎麼說。總之,這裏是原代碼:使用Apache-POI庫獲取單元格內容時,我同時得到「無法從文本單元格獲取數值」及其相反的結果。我如何解決它?
private void readFile(String excelFileName) throws FileNotFoundException, IOException {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFileName));
if (workbook.getNumberOfSheets() > 1){
System.out.println("Please make sure there is only one sheet in the excel workbook.");
}
XSSFSheet sheet = workbook.getSheetAt(0);
int numOfPhysRows = sheet.getPhysicalNumberOfRows();
XSSFRow row;
XSSFCell num;
for(int y = 1;y < numOfPhysRows;y++){ //start at the 2nd row since 1st should be category names
row = sheet.getRow(y);
poNum = row.getCell(1);
item = new Item(Integer.parseInt(poNum.getStringCellValue());
itemList.add(item);
y++;
}
}
private int poiConvertFromStringtoInt(XSSFCell cell){
int x = Integer.parseInt(Double.toString(cell.getNumericCellValue()));
return x;
}
我收到以下錯誤:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)
即使我改變它使用XSSFCell.getStringCellValue()
甚至XFFSCell.getRichTextValue
得到一個字符串,我得到的反上面的錯誤信息(並且我確保最終使用Integer.parseInt(XSSFCell.getStringCellValue()
來使其成爲int)。然後
錯誤讀取:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell
at org.apache.poi.xssf.usermodel.XSSFCell.typeMismatch(XSSFCell.java:781)
at org.apache.poi.xssf.usermodel.XSSFCell.getNumericCellValue(XSSFCell.java:199)
我知道一個事實,即Excel電子表格列實際上是一個字符串。我無法更改Excel表格,因爲它始終使用相同的格式和格式化每個列首先佔用大量處理時間。
有什麼建議嗎?
[解決方法]這裏是我想出了從@ Wivani的幫助下解決方案代碼:
private long poiGetCellValue(XSSFCell cell){
long x;
if(cell.getCellType() == 0)
x = (long)cell.getNumericCellValue();
else if(cell.getCellType() == 1)
x = Long.parseLong(cell.getStringCellValue());
else
x = -1;
return x;
}
檢查API;有方法來查詢列的類型,所以你可以用它來檢查你是否需要轉換。 PS該代碼片段不足以真正幫助您調試。 – Wivani
爲了讓大家知道發生了什麼事,我發現前100個數字有一個前導0.這導致excel自動將它作爲一個字符串。所以我不得不寫一種方法來首先檢查類型,然後相應地進行格式化。謝謝@Wivani – crstamps2
有趣的或許將來的參考添加您的'解決方案代碼'? – Wivani