質問が少しわかりにくいと思いますが、他にどのように表現すればよいかわかりませんでした。とにかく、ここに元のコードがあります:
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
、上記のエラー メッセージの逆が表示されます (最終的には を使用して int にするようにしていますInteger.parseInt(XSSFCell.getStringCellValue()
)。
エラーは次のようになります。
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;
}