使用Java设置所有types的Excel单元格值

我有一个要求从一张表复制Excel行到另一个。 但是在复制而不是实际值之后,我得到了不同的值。 有string值的单元格没有问题,但带有数字值。 Excel单元格可以包含任何types的值。 我的代码应该接受所有这些,并将其复制到另一张表中。 请帮助我在这种情况下。

if(row.getCell(getLastCell)!=null && ((row.getCell(getLastCell).toString().equalsIgnoreCase(FAIL))|| (row.getCell(getLastCell).toString().equalsIgnoreCase("Invalid CR Statement")))) { failuresRow=failuresSheet.createRow(createNewRow++); for(int ii=0;ii<=getLastCell;ii++) { failuresCell=failuresRow.createCell(ii); failuresCell.setCellValue(row.getCell(ii)+""); failuresCell.setCellType(row.getCell(ii).getCellType()); failuresCell.setCellStyle(row.getCell(ii).getCellStyle()); } } 

我知道row.getCell(ii)+“”是将types单元格转换为string,但我想设置setCellValue接受单元格可以有任何types的数据(例如:date,Bollean,string,数字,… ……)

我已经尝试使用DataFormatter,在其他方式也如下,但没有用。

  failuresCell.setCellValue(df.formatCellValue(row.getCell(ii))); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: failuresCell.setCellValue(cell.getRichStringCellValue().getString()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { failuresCell.setCellValue(cell.getDateCellValue()); } else { failuresCell.setCellValue(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: failuresCell.setCellValue(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: failuresCell.setCellValuec(cell.getCellFormula()); break; default: // some code } 

如果单元格的数值为9200278,则输出为1717.我不明白我在做什么错误。 请帮助我在这种情况下。

这是因为你正在获取单元格而不是值。 你可以使用下面的方法来代替row.getCell(int).toString()

 row.getCell(int).getStringCellValue(); row.getCell(int).getNumericCellValue(); and etc. 

只需在调用方法之前检查单元格的types。 这是一个例子:

 if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) { row.getCell(int).getBooleanCellValue(); } else if (cellType == HSSFCell.CELL_TYPE_ERROR) { row.getCell(int).getErrorCellValue(); } else if (cellType == HSSFCell.CELL_TYPE_FORMULA) { row.getCell(int).getCellFormula(); } else if (cellType == HSSFCell.CELL_TYPE_NUMERIC) { row.getCell(int).getNumericCellValue(); } else if (cellType == HSSFCell.CELL_TYPE_STRING) { row.getCell(int).getStringCellValue(); } 

我只是将它们全部设置为串。

 try { FileInputStream fileInputStream = new FileInputStream(excelTemplate); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); for (int i=0; i < workbook.getNumberOfSheets(); i++) { for (Row row : workbook.getSheetAt(i)) { for (Cell cell : row) { if (cell != null) cell.setCellType(Cell.CELL_TYPE_STRING); } } } } catch (IOException e) { e.printStackTrace(); }