功能:将Excel中的数据导入数据表。
需要的jar包如下:
下载地址:
http://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1
要保证jar包的版本一致,这里都用了3.16,commons-collections使用了4-4.1,4.0经验证不行。
poi读取excel关键代码
private Map<Object,Object> readExcelValue0(Workbook wb) {
//总行数
int totalRows = 0;
int sheetRows = 0;
//总条数
int celllength = 0;
List<String> sheetNamList = new ArrayList<>();
List<List<String>> headerList = new ArrayList<List<String>>();
int sheetNum = wb.getNumberOfSheets();
//获取sheet页名称
for(int i=0;i<sheetNum;i++) {
sheetNamList.add(wb.getSheetName(i));
Sheet sheet = wb.getSheetAt(i);
sheetRows = sheet.getPhysicalNumberOfRows();//包含表头
totalRows = totalRows + sheetRows - 1;
if (sheetRows >= 1 && sheet.getRow(0) != null) {
celllength = sheet.getRow(0).getPhysicalNumberOfCells();
}
Row row = sheet.getRow(0);
List<String> oneList = new ArrayList<String>();
for (int c = 0; c < celllength; c++) {
Cell cell = row.getCell(c);
if (cell != null) {
oneList.add(cell.getStringCellValue());
}
}
headerList.add(oneList);
}
Map<Object,Object> map = new HashMap<>();
map.put("sheetNames", sheetNamList);
map.put("headers", headerList);
map.put("totalRows", totalRows);
return map;
}
/*
* 判断excel是03还是07
*/
public boolean getExcelInfo(String fileName) {
//String fileName = mFile.getOriginalFilename();
boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
/*if (!validateExcel(fileName)) {// 验证文件名是否合格 ,放到前端
return false;
} */
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
return isExcel2003;
}
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}