传入excel文件对象,数据格式可以包括数值,文本,时间
返回list集合(一行数据是一个list)
public static List<List<String[]>> getExcelData(File file) {
HSSFWorkbook workbook;
List<List<String[]>> dataList = new ArrayList<List<String[]>>();
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet;
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
sheet = workbook.getSheetAt(i);
List<String[]> rows = new ArrayList<String[]>();
int colsnum = 0;
for (int j = 1; j <= sheet.getLastRowNum(); j++) {
HSSFRow row = sheet.getRow(j);
if (row != null) {
colsnum = sheet.getRow(1).getPhysicalNumberOfCells();
String[] cols = new String[colsnum];
for (int k = 0; k < colsnum; k++) {
Cell cell = row.getCell(k);
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
cols[k] = formater.format(date);
} else if (String.valueOf(cell.getNumericCellValue()).contains(".")) {
DecimalFormat df = new DecimalFormat("#");
cols[k] = df.format(cell.getNumericCellValue());
} else {
cols[k] = (cell + "").trim();
}
continue;
default:
cols[k] = (cell + "").trim();
continue;
}
} else {
cols[k] = "";
}
}
rows.add(cols);
}
}
dataList.add(rows);
}
} catch (IOException e) {
e.printStackTrace();
}
return dataList;
}
传入时间字符串,返回Timetamp格式时间
public static Timestamp toDate(String basicDate){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Timestamp ts = null;
try {
ts = new Timestamp(dateFormat.parse(basicDate).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return ts;
}
参考:https://blog.youkuaiyun.com/qx30339/article/details/54020308