java实现excel导入功能

想要实现一个导入excel的功能,这个excel表有很多,但是每个表的列名都不一样,怎么实现这个功能,哪位可以告诉告诉我


```java
这是service
  /**
     * 上传
     * @param file
     * @return
     */
    String readExcelFile( MultipartFile file);
service实现:
    @Override
    public String readExcelFile(MultipartFile file) {
        String result ="";
        ReadExcel readExcel=new ReadExcel();

        List projectList = readExcel.getExcelInfo(file);
        System.out.println("projectList"+projectList);

        super.saveBatch(projectList);
        if(projectList != null && !projectList.isEmpty()){
            result = "上传成功";
        }else{
            result = "上传失败";
        }
        return result;
    }
这是controller:
  @RequestMapping(value="/upload",method = RequestMethod.POST)
  @ResponseBody
  public ApiResult upload(@RequestParam(value="file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
    String result = projectService.readExcelFile(file);
    return ApiResult.ok(result);
这是工具类
package com.example.utils;

import com.example.entity.Project;
import com.example.mapper.ProjectMapper;
import com.example.mapper.ProjectProgressMapper;
import com.example.service.ProjectProgressService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ReadExcel {
    @Autowired
    private ProjectProgressService projectProgressService;
    @Autowired
    private ProjectProgressMapper projectProgressMapper;
    @Autowired
    private ProjectMapper projectMapper;
    private static ReadExcel readExcel;

   @PostConstruct
public void init() {
        readExcel = this;
    }

    // 总行数
    private int totalRows = 0;
    // 总条数
    private int totalCells = 0;
    // 错误信息接收器
    private String errorMsg;

    // 构造方法
    public ReadExcel() {
    }

    // 获取总行数
    public int getTotalRows() {
        return totalRows;
    }

    // 获取总列数
    public int getTotalCells() {
        return totalCells;
    }

    // 获取错误信息
    public String getErrorInfo() {
        return errorMsg;
    }


/**
     * 读EXCEL文件,获取信息集合
     *
     * @param mFile
     * @return
     *//*
*/

    public List getExcelInfo(MultipartFile mFile) {
        List projectList = null;
        String fileName = mFile.getOriginalFilename();// 获取文件名
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            projectList = createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return projectList;
    }

    public static void main(String[] args) {
        ReadExcel readExcel = new ReadExcel();
        String fileName = "C:/Users/Administrator/Desktop/科研管理系统项目核对-王改.xlsx";
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        List excel = readExcel.createExcel(fileInputStream, false);
        for(Project project : excel) {
            System.out.println(project);
        }
       // super.saveBatch(excel);
    }
    /**
     * 根据excel里面的内容读取项目信息
     *
     * @param is   输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */

    public static List createExcel(InputStream is, boolean isExcel2003) {
        List projectList = null;
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            ReadExcel readExcel = new ReadExcel();
            projectList = readExcel.readExcelValue(wb);// 读取Excel里面项目的信息
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        return projectList;
    }

/**
     * 读取Excel里面项目的信息
     *
     * @param wb
     * @return
     *//*
*/
//public static void main(String[] args) {
//    System.out.println(String.valueOf(new Date()));
//}
    private List readExcelValue(Workbook wb) throws ParseException {
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        this.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List projectsList = new ArrayList();
        // 循环Excel行数
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            Project project = new Project();

            // 循环Excel的列
            for (int c = 0; c < this.totalCells; c++) {
                project.setUserId(Long.valueOf(1));
                project.setOrganizationId(Long.valueOf(6));
                Cell cell = row.getCell(c);
                if (null != cell) {
                    //学科
                    if (c == 0) {
                        project.setBranchOfLearning(cell.getStringCellValue());//名称
//                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String branchOfLearning = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setBranchOfLearning(branchOfLearning.substring(0 , branchOfLearning.length() -2 > 0 ? branchOfLearning.length() -2 : 1));
//                        } else {
//                            project.setBranchOfLearning(cell.getStringCellValue());//名称
//                        }
                    }
                    //类别
                    else if (c == 1) {
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == CellType.NUMERIC) {
                            String projectType = String.valueOf(cell.getNumericCellValue());
                            project.setProjectTypeName(projectType);// 名称
                            int p = 0;
                            if (projectType.contains("纵向")){
                                p = 1;
                            }else if (projectType.contains("横向")){
                                p = 2;
                            }
                            project.setProjectType(p);//名称
                        } else {
                            String projectTypeName = String.valueOf(cell.getStringCellValue());
                            project.setProjectTypeName(projectTypeName);// 名称
                            Integer p = 0;
                            if (projectTypeName.contains("纵向")){
                                p = 1;
                            }else if (projectTypeName.contains("横向")){
                                p = 2;
                            }
                            project.setProjectType(p);//名称
                        }
                    }
                    //立项时间
                    else if( c== 3){
//                        project.setProjectStartTime(cell.getDateCellValue());
                        String s = String.valueOf(cell.getNumericCellValue());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
                        project.setProjectStartTime(simpleDateFormat.parse(s));// 名称
                    }
                    //遗传类型
                    else if ( c == 4){//2
                        project.setGeneticType(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String geneticType = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setGeneticType(geneticType.substring(0 , geneticType.length() -2 > 0 ? geneticType.length() -2 : 1));
//                        } else {
//                            project.setGeneticType(cell.getStringCellValue());//名称
//                        }
                    }
                    else if (c == 5) {

                    }
                    //项目名称
                    else if ( c == 6){//3
                        project.setProjectName(cell.getStringCellValue());//名称
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String projectName = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setProjectName(projectName.substring(0 , projectName.length() -2 > 0 ? projectName.length() -2 : 1));
//                        } else {
//                            project.setProjectName(cell.getStringCellValue());//名称
//                        }
                    }
                    //科室
                    else if (c == 7) {//4
                        project.setDepartmentId(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String departmentId = String.valueOf(cell.getNumericCellValue());
//                            project.setDepartmentId(departmentId);// 名称
//                        } else {
//                            project.setDepartmentId(cell.getStringCellValue());// 名称
//                        }
                    }
                    //主持人
                    else if( c == 8){//5
                        project.setHost(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String host = String.valueOf(cell.getNumericCellValue());
//                            project.setHost(host);// 名称
//                        } else {
//                            project.setHost(cell.getStringCellValue());// 名称
//                        }
                    }
                    //计划名称/主持单位
                    else if( c == 9){//6
                        project.setPlanName(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String planName = String.valueOf(cell.getNumericCellValue());
//                            project.setPlanName(planName);// 名称
//                        } else {
//                            project.setPlanName(cell.getStringCellValue());// 名称
//                        }
                    }
//                    //立项时间
                    else if (c == 10) {//7
//                        project.setStartTime1(cell.getDateCellValue());
                        System.out.println(cell.getCellComment());
                        String s = String.valueOf(cell.getNumericCellValue());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM");
                        project.setStartTime1(simpleDateFormat.parse(s));// 名称
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            try {
//                                String s = String.valueOf(cell.getNumericCellValue());
//                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//                                project.setStartTime1(simpleDateFormat.parse(s));// 名称
//                            } catch (Exception e) {
//                                String s = String.valueOf(cell.getNumericCellValue());
//                                System.out.println("ssssssssss" + s);
//                                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
//                                project.setStartTime1(cell.getDateCellValue());// 名称
//                            }
//                        } else {
//                            try {
//                                String s = String.valueOf(cell.getStringCellValue());
//                                if (s.contains("/")) {
//                                    project.setStartTime1(null);// 名称
//                                } else {
//                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//                                    project.setStartTime1(simpleDateFormat.parse(s));// 名称
//                                }
//
//                            } catch (Exception e) {
//                                String s = String.valueOf(cell.getStringCellValue());
//                                if (s.contains("/")) {
//                                    project.setStartTime1(null);// 名称
//                                } else {
//                                    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
//                                    project.setStartTime1(cell.getDateCellValue());// 名称
//                                }
//
//                            }
//                        }
                    }
                    //研究起止时间
                    else if (c == 11) {//8
//                        project.setStartTime(cell.getDateCellValue());
//                        String s = String.valueOf(cell.getNumericCellValue());
//                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
                        project.setStartTime(cell.getStringCellValue());// 名称
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            try {
//                                String s = String.valueOf(cell.getNumericCellValue());
//                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//                                project.setStartTime(simpleDateFormat.parse(s));// 名称
//                            } catch (Exception e) {
//                                String s = String.valueOf(cell.getNumericCellValue());
//                                System.out.println("mmmmmmmmm" + s);
//                                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
//                                project.setStartTime(cell.getDateCellValue());// 名称
//                            }
//                        } else {
//                            try {
//                                String s = String.valueOf(cell.getStringCellValue());
//                                if (s.contains("/")) {
//                                    project.setStartTime(null);// 名称
//                                } else {
//                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//                                    project.setStartTime(simpleDateFormat.parse(s));// 名称
//                                }
//
//                            } catch (Exception e) {
//                                String s = String.valueOf(cell.getStringCellValue());
//                                if (s.contains("/")) {
//                                    project.setStartTime(null);// 名称
//                                } else {
//                                    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
//                                    project.setStartTime(cell.getDateCellValue());// 名称
//                                }
//
//                            }
//                        }
                    }
                    //项目类别
                    else if (c == 12) {
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == CellType.NUMERIC) {
                            String projectLevel = String.valueOf(cell.getNumericCellValue());
                            project.setProjectLevelName(projectLevel);
                            int i = 0;
                            if (projectLevel.contains("国家级")) {
                                i = 1;
                            } else if (projectLevel.contains("省级/自治区级")) {
                                i = 2;
                            } else if (projectLevel.contains("市级")) {
                                i = 3;
                            } else if (projectLevel.contains("院级")) {
                                i = 4;
                            }else if (projectLevel.contains("其他")){
                                i = 5;
                            }
                            project.setProjectLevel(i);// 名称
                        } else {
                            String projectLevelName = String.valueOf(cell.getStringCellValue());
                            project.setProjectLevelName(projectLevelName);
                            int i = 0;
                            if (projectLevelName.contains("国家级")) {
                                i = 1;
                            } else if (projectLevelName.contains("省级/自治区级")) {
                                i = 2;
                            } else if (projectLevelName.contains("市级")) {
                                i = 3;
                            } else if (projectLevelName.contains("院级")) {
                                i = 4;
                            }else if (projectLevelName.contains("其他")){
                                i = 5;
                            }
                            project.setProjectLevel(i);// 名称
                        }
                    }
                    //资助总额(万元)
                    else if(c == 13){
                        project.setFundingAmount(new BigDecimal(String.valueOf(cell.getNumericCellValue())));
//                        System.out.println("资助总额(万元)"+cell.toString());
//                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String fundingAmount= String.valueOf(cell.getNumericCellValue());
//                            System.out.println("资助总额a"+fundingAmount);
//                            project.setFundingAmount(new BigDecimal(fundingAmount));// 名称
//                        } else {
//                            if (StringUtils.isNotEmpty(cell.getStringCellValue()) && StringUtils.isNumeric(cell.getStringCellValue())) {
//                                System.out.println("资助总额b"+cell.getStringCellValue());
//                                project.setFundingAmount(new BigDecimal(cell.getStringCellValue()));
//                            }
//                        }
                    }
                    //资助总额备注
                    else if (c == 14) {
                        project.setFundingRemarks(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String fundingRemarks = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setFundingRemarks(fundingRemarks.substring(0 , fundingRemarks.length() -2 > 0 ? fundingRemarks.length() -2 : 1));
//                        } else {
//                            project.setFundingRemarks(cell.getStringCellValue());//名称
//                        }
                    }
                    //伦理通知
                    else if (c == 15) {
                         project.setEthicalNotice(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String ethicalNotice = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setEthicalNotice(ethicalNotice.substring(0 , ethicalNotice.length() -2 > 0 ? ethicalNotice.length() -2 : 1));
//                        } else {
//                            project.setEthicalNotice(cell.getStringCellValue());//名称
//                        }
                    }
                    //伦理审查结果
                    else if( c == 16){
                        project.setEthicalReviewResults(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if( cell.getCellType() == CellType.NUMERIC){
//                            String ethicalReviewResults = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setEthicalReviewResults(ethicalReviewResults.substring( 0 , ethicalReviewResults.length() -2 > 0 ? ethicalReviewResults.length() -2 : 1));
//                        }else {
//                            project.setEthicalReviewResults(cell.getStringCellValue());//名称
//                        }
                    }
                    //项目成员(项目参与人员排序)
                    else if( c == 17){
                        project.setProjectParticipants(cell.getStringCellValue());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if ( cell.getCellType() == CellType.NUMERIC){
//                            String projectParticipants = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setProjectParticipants(projectParticipants.substring( 0 , projectParticipants.length() -2 > 0 ? projectParticipants.length() -2 : 1));
//                        }else {
//                            project.setProjectParticipants(cell.getStringCellValue());//名称
//                        }
                    }
                    //自筹资金情况(万元)
                    else if(c == 17){
                        project.setSelfFinancing(new BigDecimal(String.valueOf(cell.getNumericCellValue())));
//                        System.out.println("自筹资金情况(万元)"+cell.toString());
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String selfFinancing= String.valueOf(cell.getNumericCellValue());
//                            System.out.println("自筹资金情况a"+selfFinancing);
//                            project.setSelfFinancing(new BigDecimal(selfFinancing));// 名称
//                        } else {
//                            if (StringUtils.isNotEmpty(cell.getStringCellValue()) && StringUtils.isNumeric(cell.getStringCellValue())) {
//                                System.out.println("自筹资金情况b"+cell.getStringCellValue());
//                                project.setSelfFinancing(new BigDecimal(cell.getStringCellValue()));
//                            }
//                        }
                    }
                    //自筹资金备注
                    else if (c == 18) {
                        project.setSelfRaisedRemarks(cell.getStringCellValue());
                    }
//                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
//                        if (cell.getCellType() == CellType.NUMERIC) {
//                            String selfRaisedRemarks = String.valueOf(cell.getNumericCellValue());
//                            //名称
//                            project.setSelfRaisedRemarks(selfRaisedRemarks.substring(0 , selfRaisedRemarks.length() -2 > 0 ? selfRaisedRemarks.length() -2 : 1));
//                        } else {
//                            project.setSelfRaisedRemarks(cell.getStringCellValue());//名称
//                        }
//                    }

                }
            }
            // 添加到list
            projectsList.add(project);
        }
        return projectsList;
    }

    private Date cellToDate(Cell dateCell) {
        if (CellType.NUMERIC == dateCell.getCellType()) {
            if (DateUtil.isCellDateFormatted(dateCell)) {
                //用于转化为日期格式
                Date d = dateCell.getDateCellValue();
                DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = formater.format(d);
                return DateUtils.toDate(date, DateUtils.YYYY_MM_DDHHMMSS);
            }
        }
        return null;
    }



/**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     *//*
*/
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // @描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }






}



```

easyui 已经帮你实现了
或者自己使用反射来实现