public class ExcelUtil {
public static Log log = LogFactory.getLog(ExcelUtil.class);
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 判断数据的类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 数字
//如果为时间格式的内容
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
cellValue=sdf.format(HSSFDateUtil.getJavaDate(cell.
getNumericCellValue())).toString();
break;
} else {
HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
String cellFormatted = dataFormatter.formatCellValue(cell);
log.info("数字类型=="+cellFormatted+"==");
cellValue=cellFormatted;
}
break;
case Cell.CELL_TYPE_STRING: // 字符串
// log.info("==字符串类型==");
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: // 公式
log.info("==公式=="+cell.getCellStyle().getDataFormatString());
if (cell.getCellStyle().getDataFormatString().indexOf("%") != -1) {
cellValue=cell.getNumericCellValue()*100+"%";
}
break;
case Cell.CELL_TYPE_BLANK: // 空值
cellValue = null;
break;
case Cell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}
百分比问题:
case Cell.CELL_TYPE_FORMULA: // 公式 if (cell.getCellStyle().getDataFormatString().indexOf("%") != -1) { //此字符串中没有这样的字符,则返回 -1 double a=cell.getNumericCellValue(); log.info("公式中原始值=="+a); double b=a*100; log.info("===乘100后=="+b); // NumberFormat nf = NumberFormat.getNumberInstance(); // // 保留两位小数 // nf.setMaximumFractionDigits(2); // // 如果不需要四舍五入,可以使用RoundingMode.DOWN // nf.setRoundingMode(RoundingMode.UP); // String c= nf.format(b); // log.info("保留两位小数并四舍五入=="+c); // cellValue= c+"%"; String c=String.format("%.2f", b); log.info("保留两位小数并四舍五入=="+c); cellValue= c+"%"; } break;
公式中原始值==1.6616989098241854
===乘100后==166.16989098241854
保留两位小数并四舍五入==166.17