Excel文件读取
Class ReadExcelFile{
public static Map<String, JSONArray> readExcelData(String exclePath) {
Workbook wb = null;
Sheet sheet = null;
Row row = null;
List<Map<String, ExcelPojo>> list = null;
String[] columns = {};// 存放Excel中的列名
wb = readExcel(exclePath);// Excel文件读取
if (wb != null) {
list = new ArrayList<Map<String, ExcelPojo>>();// 用来存放表中数据
sheet = wb.getSheetAt(0); // 获取第一个sheet
int maxRow = sheet.getPhysicalNumberOfRows();// 获取最大行数
keys = new ArrayList<String>();// 存放key
row = sheet.getRow(0);// 获取第一行
if (row == null) {
System.out.println("OperationExcel.main():Excel第一行表头为空!!");
}
int maxColumn = row.getPhysicalNumberOfCells(); // 获取最大列数
// 保存表头的字段名
Map<String, Integer> nameMap = new HashMap<String, Integer>();
columns = new String[maxColumn];
for (int i = 0; i < maxColumn; i++) {// 遍历第一行数据,保存数据表头
columns[i] = (String) getCellFormatValue(row.getCell(i));
if (StringUtils.isNotEmpty(columns[i])) {
nameMap.put(columns[i], i);
}
}
Map<String, JSONArray> rowMap = new HashMap<String, JSONArray>();
// 提取数据
for (int i = 1; i < maxRow; i++) {// 从第二行开始遍历所有行
row = sheet.getRow(i);// Excel中的第i行
if (row != null) {// 开始提取行内数据
String id = (String) getCellFormatValue(row.getCell(nameMap.get("id")));//唯一标识
String score = (String) getCellFormatValue(row.getCell(nameMap.get("score")));
String name = (String) getCellFormatValue(row.getCell(nameMap.get("name")));
String gender = (String) getCellFormatValue(row.getCell(nameMap.get("gender")));
//构建JSONObject对象
JSONObject json = new JSONObject();
json.put("id",id);
json.put("score",score);
json.put("name",name);
json.put("gender",gender);
rowMap.add(id,json);
} else {
break;
}
}
return rowMap;
}
return null;
}
/**
* 获取表格中的数据
*
* @param cell
* @return
*/
public static Object getCellFormatValue(Cell cell) {
Object cellValue = null;
if (cell != null) {
// 判断cell类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: {
cellValue = String.valueOf((long) cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_FORMULA: {
// 判断cell是否为日期格式
if (DateUtil.isCellDateFormatted(cell)) {
// 转换为日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue();
} else {
// 数字
cellValue = cell.getNumericCellValue();
}
break;
}
case Cell.CELL_TYPE_STRING: {
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
} else {
cellValue = "";
}
return cellValue;
}
/**
* 读取Excel文件,返回workbook对象
*
* @param filePath
* @return
*/
public static Workbook readExcel(String filePath) {
Workbook wb = null;
if (filePath == null) {
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));// 判断Excel是什么版本的
InputStream is = null;
try {
is = new FileInputStream(filePath);// 文件流对象
if (".xls".equals(extString)) {
return wb = new HSSFWorkbook(is);// Excel版本2003
} else if (".xlsx".equals(extString)) {
return wb = new XSSFWorkbook(is);// Excel版本2007/2010
} else {
wb = null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return wb;
}
}