使用POI导入Excel文档
简介
实现
- 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
- 输入文件路径,获取文件对象
Scanner sc = new Scanner(System.in);
String path = sc.next();
File file = new File(path);
- 导入文件,判断文件是否是Excel文件
String fileName = file.getName();
if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")){
System.out.println("文件格式错误");
return;
}
- 读取Excel文件,获取数据集合
ExcelReader.readExcel(file, User.class);
List<User> successList = ExcelReader.getSuccessList();
工具类源码(4.X版本需要改变Cell的数据类型):
public class ReaderExcelUtils {
private static Logger logger = Logger.getLogger(ReaderExcelUtils.class);
private static Workbook workbook = null;
private static List<Object> successList = null;
private static List<Object> failList = null;
private static volatile List<Object> successListOfThread = null;
private static volatile List<Object> failListOfThread = null;
private static FilterManager filterManager = new FilterManager(new FilterChain());
private ReaderExcelUtils(){}
public static <T> List<T> getSuccessList() {
return (List<T>) successList;
}
public static <T> List<T> getFailList() {
return (List<T>) failList;
}
private static boolean isNotEmpty(File file) throws FileNotFoundException {
if (file == null){
throw new FileNotFoundException();
}
return true;
}
private static String getFileType(File file){
String name = file.getName();
String fileType = name.substring(name.lastIndexOf(".") + 1);
return fileType;
}
public static Workbook getWorkbook(File file) throws IOException {
isNotEmpty(file);
String fileType = getFileType(file);
InputStream inputStream = new FileInputStream(file);
if (fileType != null && fileType.equalsIgnoreCase("xls")){
if (workbook == null){
workbook = new HSSFWorkbook(inputStream);
}
} else if (fileType != null && fileType.equalsIgnoreCase("xlsx")){
if (workbook == null){
workbook = new XSSFWorkbook(inputStream);
}
}
return workbook;
}
public static Workbook getWorkbookOfThread(File file) throws IOException {
isNotEmpty(file);
String fileType = getFileType(file);
InputStream inputStream = new FileInputStream(file);
if (fileType != null && fileType.equalsIgnoreCase("xls")){
if(workbook == null){
synchronized (ReaderExcelUtils.class){
if (workbook == null){
workbook = new HSSFWorkbook(inputStream);
}
}
}
} else if(fileType != null && fileType.equalsIgnoreCase("xlsx")){
if(workbook == null){
synchronized (ReaderExcelUtils.class){
if (workbook == null){
workbook = new XSSFWorkbook(inputStream);
}
}
}
}
return workbook;
}
public static Workbook getWorkbookOfThread(Boolean bool, File file) throws IOException {
if(bool == true){
return getWorkbookOfThread(file);
}else {
return getWorkbook(file);
}
}
public static <T> List<T> createSuccessListOfThread(Boolean bool){
if (bool == true){
if (successListOfThread == null){
synchronized (ReaderExcelUtils.class){
if (successListOfThread == null){
successListOfThread = new ArrayList<>();
return (List<T>) successListOfThread;
}
}
}
} else{
successList = new ArrayList<>();
return (List<T>) successList;
}
return null;
}
public static <T> List<T> createFailListOfThread(Boolean bool){
if (bool == true){
if (failListOfThread == null){
synchronized (ReaderExcelUtils.class){
if (failListOfThread == null){
failListOfThread = new ArrayList<>();
return (List<T>) failListOfThread;
}
}
}
} else{
failList = new ArrayList<>();
return (List<T>) failList;
}
return null;
}
public static <T> void readExcelOfThread(Boolean threadBool, File file, Class<T> clazz, ExcelDataFilter filter) throws Exception {
isNotEmpty(file);
Workbook workbook = getWorkbookOfThread(threadBool, file);
T t = null;
List<Object> failDataList = createFailListOfThread(threadBool);
List<Object> successDataList = createSuccessListOfThread(threadBool);
for (int i = 0; i < workbook.getNumberOfSheets(); i ++){
Sheet sheet = workbook.getSheetAt(i);
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (firstRow == null){
throw new ParsingException("解析Excel数据异常");
}
int endRowNum = sheet.getPhysicalNumberOfRows();
int startRowNum = firstRowNum + 1;
for(int j = startRowNum; j < endRowNum; j ++){
Row row = sheet.getRow(j);
HashMap<String, Object> data = paresRowData(sheet, row, clazz, filter);
Boolean bool = (Boolean) data.get("status");
Object obj = data.get("data");
if (bool == true){
successDataList.add(obj);
}else {
failDataList.add(obj);
}
}
}
if (threadBool == true){
successListOfThread = successDataList;
failListOfThread = failDataList;
}else{
successList = successDataList;
failList = failDataList;
}
}
public static <T> HashMap<String, Object> paresRowData(Sheet sheet, Row row, Class<T> clazz, ExcelDataFilter filter) throws IllegalAccessException, InstantiationException, InvocationTargetException {
Object obj = clazz.newInstance();
HashMap<String, Object> map = new HashMap<>();
map.put("status", true);
Cell cell = null;
Field[] fields = clazz.getDeclaredFields();
ArrayList<Field> list = new ArrayList<>();
for (Field field : fields) {
if(field.isAnnotationPresent(EntityExcel.class)){
list.add(field);
}
}
Method[] methods = clazz.getDeclaredMethods();
int size = list.size();
Row head = sheet.getRow(0);
for (int i = 0; i < head.getLastCellNum(); i++) {
Cell cell1 = head.getCell(i);
String cellName = parseCellDataToString(cell1);
for (int j = 0; j < size; j ++){
Field field = list.get(j);
if (cellName.equals(field.getAnnotation(EntityExcel.class).name())){
if (map.containsKey("message")){
break;
}
map.remove("message");
cell = row.getCell(i);
Object value = parseCellDataToString(cell);
String valueStr = value + "";
String str = list.get(j).getName();
Class<?> type = list.get(j).getType();
String fieldName = str.substring(0,1).toUpperCase().concat(str.substring(1).toLowerCase());
String methodName = "set" + fieldName;
if (type == Byte.class){
try {
value = Byte.parseByte(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Integer.class){
try {
value = Integer.parseInt(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Long.class){
try {
value = Long.parseLong(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Short.class){
try {
value = Short.parseShort(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Float.class){
try {
value = Float.parseFloat(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Double.class){
try{
value = Double.parseDouble(valueStr);
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Boolean.class){
try{
if ("是".equals(valueStr) || "true".equalsIgnoreCase(valueStr) || "yes".equalsIgnoreCase(valueStr) || "1".equals(valueStr)){
value = true;
}else {
value = false;
}
} catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}else if (type == Character[].class){
try{
value = valueStr.toCharArray();
}catch (Exception e){
map.put("status", false);
map.put("message", "数据类型错误");
value = null;
}
}
if (filter != null){
filterManager.setFilter(filter);
try {
filterManager.executeRowExcelData(obj);
} catch (Exception e){
map.put("message", e.getMessage());
map.put("status", false);
}
}
if (map.containsKey("message")){
for (Method method : methods) {
if (method.getName().equals("setErrorMsg")){
method.invoke(obj, map.get("message"));
break;
}
}
continue;
}
for (Method method : methods) {
if (method.getName().equals(methodName)){
method.invoke(obj, value);
break;
}
}
break;
}
}
}
map.remove("message");
map.put("data", obj);
return map;
}
public static String parseCellDataToString(Cell cell){
if (cell == null){
return null;
}
String value = null;
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:
double numericCellValue = cell.getNumericCellValue();
value = new DecimalFormat("0").format(numericCellValue);
break;
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue() + "";
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula();
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
default:
break;
}
return value;
}
}