我需要读取excel表格中的数据.在一个单元格中,数据是30.44%,但当我从单元格中读取数据时,输出是0.3044,而我需要的输出是30.44%,因为它是来自excel的。
public String getDataFromExcelWithColNo(String sheetname, String colno, String rowno) {
String data = null;
try {
workbook = new XSSFWorkbook(filepath);
sheet = workbook.getSheet(sheetname);
XSSFRow firstrow = sheet.getRow(Integer.parseInt(rowno));
int col = Integer.parseInt(colno);
try {
int celltype = sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getCellType();
if (celltype == XSSFCell.CELL_TYPE_STRING) {
data = sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getStringCellValue().toString()
.trim();
System.out.println("Value: " + data);
} else if (celltype == XSSFCell.CELL_TYPE_NUMERIC) {
data = Double.toString(
sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getNumericCellValue());
} else if (celltype == XSSFCell.CELL_TYPE_BOOLEAN) {
data = String.valueOf(
sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getBooleanCellValue());
}
} catch (NullPointerException ne) {
System.out.println("Returning null value.");
data = "";
}
} catch (IOException io) {
}
return data;
}
你可以通过测试单元格的数据格式来发现一个单元格的格式是否为百分数
else if (celltype == CellType.NUMERIC) {
if (cellstyle.getDataFormatString().contains("%")) {
data = Double.toString(sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getNumericCellValue()*100);
System.out.println("Value: " + data + "%");
} else {
data = Double.toString(sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getNumericCellValue());
System.out.println("Value: " + data);
}
完整的块 。
try {
CellType celltype = sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getCellType();
CellStyle cellstyle = sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getCellStyle();
if (celltype == CellType.STRING) {
data = sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getStringCellValue().toString()
.trim();
System.out.println("Value: " + data);
} else if (celltype == CellType.NUMERIC) {
if (cellstyle.getDataFormatString().contains("%")) {
data = Double.toString(sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getNumericCellValue()*100);
System.out.println("Value: " + data + "%");
} else {
data = Double.toString(sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getNumericCellValue());
System.out.println("Value: " + data);
}
} else if (celltype == CellType.BOOLEAN) {
data = String.valueOf(
sheet.getRow((Integer.parseInt(rowno)) - 1).getCell(col - 1).getBooleanCellValue());
}
} catch (NullPointerException ne) {
System.out.println("Returning null value.");
data = "";
}
}