packagepoi;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.text.DecimalFormat;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.apache.poi.ss.usermodel.CellStyle;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFRow;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public classGetExcelData {public static List>readFile(File file){//excel中第几列 : 对应的表头
Map colAndNameMap = new HashMap<>();
List> resultList = new ArrayList<>();
FileInputStream fs= null;
XSSFWorkbook wb= null;try{
fs= newFileInputStream(file);
wb= newXSSFWorkbook(fs);for(int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++){//获取sheet数据
XSSFSheet st =wb.getSheetAt(sheetIndex);//遍历一个sheet中每一行
for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) {//表头:值
Map nameAndValMap = new HashMap<>();//获取到一行数据
XSSFRow row =st.getRow(rowIndex);for(int cellIndex = 0; cellIndex < row.getPhysicalNumberOfCells(); cellIndex++){if(rowIndex==0){
colAndNameMap.put(cellIndex, row.getCell(cellIndex).getStringCellValue());
}else if(!colAndNameMap.isEmpty()){
nameAndValMap.put(cellIndex, buildDate(row.getCell(cellIndex)));
}
}if(!nameAndValMap.isEmpty()){
resultList.add(nameAndValMap);
}
}
}returnresultList;
}catch(FileNotFoundException e) {
System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");
e.printStackTrace();
}catch(IOException e) {
System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");
e.printStackTrace();
}catch(Exception e) {
System.out.println(">>>>>>>>>> 读取excel文件时出错了!!!");
e.printStackTrace();
}finally{try{
wb.close();
}catch(IOException e) {
e.printStackTrace();
}try{
fs.close();
}catch(IOException e) {
e.printStackTrace();
}
}return null;
}//将excel中时间格式字段进行处理
@SuppressWarnings("deprecation")public staticString buildDate(XSSFCell cell) {
String result= newString();switch(cell.getCellType()) {caseXSSFCell.CELL_TYPE_NUMERIC:if (cell.getCellStyle().getDataFormat() == 176) {//处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");double value =cell.getNumericCellValue();
Date date=org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
result=sdf.format(date);
}else{double value =cell.getNumericCellValue();
CellStyle style=cell.getCellStyle();
DecimalFormat format= newDecimalFormat();
String temp=style.getDataFormatString();//单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
result=format.format(value);
}break;case XSSFCell.CELL_TYPE_STRING://String类型
result =cell.getStringCellValue();break;default:
result= "";break;
}returnresult;
}
}