Java Springboot MultipartFile 进行Excel文件解析,并返回list map 对象 - 工具类

Java Springboot MultipartFile 进行Excel文件解析,并返回list map 对象

主要实现代码如下:


import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: Vinfol
 * @Email: [email protected]
 */
@Slf4j
public class ExcelUtil {
    /**
     * 导入数据,获取excel数据,仅支持xls/xlsx格式
     *
     * @param multipartFile
     * @param classObj
     * @return
     */
    public static List> readDataFromExcelXlsOrXlsx(MultipartFile multipartFile, Class classObj) {
        try {
            //对前端传递的文件进行校验
            if (multipartFile == null && multipartFile.getSize() == 0) {
                throw new PortalException(-1L, "文件为空,上传错误,重新上传");
            }
            //获取文件名称 判断文件是否为 Execl
            String filename = multipartFile.getOriginalFilename();
            InputStream inputStream = multipartFile.getInputStream();
            //根据文件格式 对应不同的api解析
            String type = "";
            if (filename.endsWith(".xlsx")) {
                type = "xlsx";
            } else if (filename.endsWith(".xls")) {
                type = "xls";
            }
            return readExcelXlsOrXlsx(inputStream, type, classObj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取xls/xlsx文件 ,只解析第一张sheet
     *
     * @param inputStream
     * @param type
     * @return
     * @throws IOException
     */
    private static List> readExcelXlsOrXlsx(InputStream inputStream, String type, Class classObj) throws IOException {

        //读取第一张sheet ,
        Sheet sheet = null;
        if (type.equals("xls")) {
            HSSFWorkbook sheets = new HSSFWorkbook(inputStream);
            sheet = sheets.getSheetAt(0);
        } else if (type.equals("xlsx")) {
            XSSFWorkbook sheets1 = new XSSFWorkbook(inputStream);
            sheet = sheets1.getSheetAt(0);
        } else {
            throw new PortalException(-1L, "解析文件类型错误");
        }
        Map objectFieldToMap = getObjectFieldToMap(classObj);
        Row rowHeader = sheet.getRow(0); //  首行为 表头
        Map indexToColumnNameMap = new HashMap<>();
        for (int i = 0; i < rowHeader.getLastCellNum(); i++) {
            rowHeader.getCell(i).setCellType(CellType.STRING);
            String stringCellValue = rowHeader.getCell(i).getStringCellValue();
            indexToColumnNameMap.put(i, objectFieldToMap.getOrDefault(stringCellValue, stringCellValue));
        }
        List> ehicleViolatsion = new ArrayList<>();
        for (int rowNum = 2; rowNum < sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row != null) {
                Map rowData = new HashMap<>();
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    row.getCell(i).setCellType(CellType.STRING);
                    String stringCellValue0 = row.getCell(i).getStringCellValue();
                    rowData.put(indexToColumnNameMap.get(i), stringCellValue0);
                }
                ehicleViolatsion.add(rowData);
            }
        }
        return ehicleViolatsion;
    }


    public static  Map getObjectFieldToMap(Class entityClass) {
        Field[] fields = entityClass.getFields();
        Map mapResult = new HashMap<>();
        for (Field field : fields) {
            field.setAccessible(true); // 设置可访问,以便访问私有字段
            field.setAccessible(true); // 设置可访问,以便访问私有字段
            // 检查字段上是否有 @ExcelNameAnno 注解
            ExcelNameAnno annotationName = field.getAnnotation(ExcelNameAnno.class);
            if (annotationName == null || StringUtils.isEmpty(annotationName.name())) {
                continue; // 如果没有该注解,取消使用该字段映射
            }
            String columnName = field.getName();
            log.info("annotationName:{}, columnName:{}", annotationName.name(), columnName);
            mapResult.put(annotationName.name(), columnName);
        }
        return mapResult;
    }
}

你可能感兴趣的:(java,java,spring,boot,excel)