Excel表格导入时时间格式出现毫秒数和时间格式,字符串格式解决方式,获取元素Cell有个getCellType方法判断是什么类型再进行转换。
Excel 将信息收集到后,通过数据上传的方式,将数据放到数据库中,而如果在操作的过程中没有把excel的数据类型对应的获取,就会报错,下面写了一个方法将row的每一个cell转换成String类型,
int type = cell.getCellType(); //获取cell的类型,分别有
CellType 类型 值
CELL_TYPE_NUMERIC 数值型 0
CELL_TYPE_STRING 字符串型 1
CELL_TYPE_FORMULA 公式型 2
CELL_TYPE_BLANK 空值 3
CELL_TYPE_BOOLEAN 布尔型 4
CELL_TYPE_ERROR 错误 5
将某个Cell 设置成String row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
处理日期相对要麻烦一点,先获取日期的样式
String string_type =cell.getCellStyle().getDataFormatString();
并且该格子得设置成数值型的,
String ans = new SimpleDateFormat(“yyyy-MM-dd”).format(cell.getDateCellValue());
这样ans就能获取到String类型的日期了,不然只能获取一个5位的数字
出现这几种类似情况都可以解决,还有什么问题评论一起解决,感谢!
String filePath = "C:\\Users\\gcs-7\\Desktop\\测试.xlsx";
// 判断是否为excel类型文件
if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
System.out.println("文件不是excel类型");
}
FileInputStream fis = null;
Workbook wookbook = null;
int lineNum = 0;
Sheet sheet = null;
try {
// 获取一个绝对地址的流
fis = new FileInputStream(filePath);
// 2003版本的excel,用.xls结尾, 2007版本以.xlsx
if (filePath.endsWith(".xls")) {
wookbook = new HSSFWorkbook(fis);// 得到2003版结尾.xls工作簿
} else {
wookbook = new XSSFWorkbook(fis);// 得到2007版结尾.xlsx工作簿
}
// 得到一个工作表
sheet = wookbook.getSheetAt(0);
// 获得表头
Row rowHead = sheet.getRow(0);
// 列数
int rows = rowHead.getPhysicalNumberOfCells();
// 行数
lineNum = sheet.getLastRowNum();
if (0 == lineNum) {
System.out.println("Excel内没有数据!");
}
// 获得所有数据
for (int i = 1; i <= lineNum; i++) {
// 获得第i行对象
Row row = sheet.getRow(i);
for (int j = 0; j < rows; j++) {
Cell cell = row.getCell(j);
if(cell!=null && cell.toString()!=""){
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyyMMdd");
}
Date date = cell.getDateCellValue();
String result = sdf.format(date);
System.out.println("毫秒数格式:"+result);
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING){
System.out.println("字符串格式:"+cell.getStringCellValue());
//date=cell.getDateCellValue();
}else if(cell.getCellStyle().getDataFormat()==HSSFDataFormat.getBuiltinFormat("yyyyMMdd")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.parse(cell.getRichStringCellValue().getString());
System.out.println("时间格式:"+cell.getStringCellValue());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}