使用mybatisplus快速开发springboot项目(五)--Excel导入

使用mybatisplus快速开发springboot项目(四)--PageHelper-CSDN博客

很多情况下,数据需要一条一条的添加,使用excel表格的方式会大大提高操作的效率~

现在引入poi库帮我们实现excel文件的导入

pom.xml导入依赖

    <!--使用POI读取文件-->
        <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>

ImportExcelUtil(导入Excel工具类)

package com.example.examservice.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 导入Excel表工具类
 */
public class ImportExcelUtil {
    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws Exception
     */
    public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = ImportExcelUtil.getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(ImportExcelUtil.getCellValue(cell));
                }
                list.add(li);
            }

        }
//        work.close();
        return list;
    }

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    /**
     * 描述:对表格中数值进行格式化
     * @param cell
     * @return
     */
    public  static Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
//        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字

        if (cell!=null){
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getRichStringCellValue().getString();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if("General".equals(cell.getCellStyle().getDataFormatString())){
                        value = df.format(cell.getNumericCellValue());
                    }
                    else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                        value = sdf.format(cell.getDateCellValue());
                    }
                    else{
                        value = sdf.format(cell.getDateCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                default:
                    break;
            }
        }

        return value;
    }
}

导入业务实现

package com.example.examservice.comprehensiveService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.examservice.common.CustomException;
import com.example.examservice.common.R;
import com.example.examservice.entity.Course;
import com.example.examservice.entity.Question;
import com.example.examservice.service.CourseService;
import com.example.examservice.service.QuestionService;
import com.example.examservice.utils.ImportExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  综合服务类
 * </p>
 *
 * @author liujianchen
 * @since 2024-03-19
 */
@Slf4j
@Transactional
@Service
public class QuestionBankService {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private CourseService courseService;

    public R importExcelQuestion(MultipartFile file) {
        int j = 0;
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Course::getIsDeleted, 0);
        List<Course> courseList = courseService.list(queryWrapper);
        try {
            //验证文件类型
            if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")
                    &&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
                throw new CustomException("文件类型有误!请上传Excle文件");
            }
            //获取数据
            List<List<Object>> olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
            List<Question> questionList = new ArrayList<>();
            for (int i = 0; i < olist.size(); i++) {
                List<Object> list = olist.get(i);
                Question question = new Question();
                question.setId(IdWorker.getId());
                //根据下标获取每一行的每一条数据
                if (StringUtils.isBlank(String.valueOf(list.get(0))))
                    throw new CustomException("第" + j + "题题目不能为空");
                question.setQuestion(String.valueOf(list.get(0)));

                if (StringUtils.isBlank(String.valueOf(list.get(1))))
                    throw new CustomException("第" + j + "题类型不能为空");
                String type = String.valueOf(list.get(1));

                if (type.contains("填空")) {
                    question.setType("cloze");
                } else if (type.contains("单选")){
                    question.setType("multiple_choice");
                } else if (type.contains("多选")){
                    question.setType("multiple_choice_questions");
                } else if (type.contains("判断")){
                    question.setType("true_or_false");
                } else {
                    throw new CustomException("第" + j + "题类型错误");
                }

                Object optionAValue = list.get(2);
                if (optionAValue != null)
                    question.setOptionA(String.valueOf(optionAValue));

                Object optionBValue = list.get(3);
                if (optionBValue != null)
                    question.setOptionB(String.valueOf(optionBValue));

                Object optionCValue = list.get(4);
                if (optionCValue != null)
                    question.setOptionC(String.valueOf(optionCValue));

                Object optionDValue = list.get(5);
                if (optionDValue != null)
                    question.setOptionD(String.valueOf(optionDValue));

                if (StringUtils.isBlank(String.valueOf(list.get(6))))
                    throw new CustomException("第" + j + "题答案不能为空");
                question.setAnswer(String.valueOf(list.get(6)));

                if (StringUtils.isBlank(String.valueOf(list.get(7))))
                    throw new CustomException("第" + j + "题分数不能为空");
                question.setScore(Integer.parseInt((String) list.get(7)));

                if (StringUtils.isBlank(String.valueOf(list.get(8))))
                    throw new CustomException("第" + j + "题难度不能为空");
                question.setDifficulty(Integer.parseInt((String) list.get(8)));

                String courseName = (String) list.get(9);
                if (StringUtils.isBlank(String.valueOf(list.get(9))))
                    throw new CustomException("第" + j + "题课程不能为空");
                question.setCourseName(courseName);
                // 查找与指定课程名称相同的课程,并获取其ID
                Optional<Long> courseIdOptional = courseList.stream()
                        .filter(course -> course.getName().equals(courseName))
                        .map(Course::getId)
                        .findFirst();
                Long courseId;
                // 如果不存在相同名称的课程ID,则执行操作
                if (!courseIdOptional.isPresent()) {
                    Course course = new Course();
                    courseId = IdWorker.getId();
                    course.setId(courseId);
                    course.setName(courseName);
                    course.setIsDeleted(0);
                    courseService.save(course);
                    // 保存课程后立即获取最新的课程列表
                    courseList = courseService.list(queryWrapper);
                } else
                    courseId = courseIdOptional.get(); // 获取课程ID

                question.setCourseId(courseId);
                if (questionList.add(question))
//                if (questionService.save(question))
                    j++;
                else
                    throw new CustomException("第" + j + "题保存失败");
            }
            questionService.saveBatch(questionList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return R.ok().message("成功生成"+ j +"条问题");
        }
    }
}

接口需要接收一个MultipartFile类型的数据

用postman做示例

test.xls值就是我们的excel文件

搞定~

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用Mybatis-Plus自动生成代码的步骤如下: 1. 首先,在pom.xml文件中添加Mybatis-Plus的依赖项。这包括mybatis-plus-generator、velocity-engine-core和lombok等依赖项。\[1\] 2. 创建一个Mapper接口,继承自BaseMapper,并指定实体类的泛型。在这个接口中,你可以定义自己的查询方法。\[3\] 3. 配置Mybatis-Plus的代码生成器。你可以使用代码生成器来生成Mapper、Model、Service和Controller层的代码。你可以使用代码或者Maven插件来快速生成代码。\[2\] 4. 运行代码生成器,生成所需的代码文件。 5. 在Spring Boot的配置文件中配置数据库连接信息和Mybatis-Plus的相关配置。 6. 在Service层中使用生成的Mapper接口进行数据库操作。 通过以上步骤,你可以在Spring Boot中使用Mybatis-Plus自动生成代码。这样可以大大减少手动编写重复的CRUD操作的工作量,并提高开发效率。 #### 引用[.reference_title] - *1* [SpringBoot中的自动代码生成 - 基于Mybatis-Plus](https://blog.csdn.net/Jalon2015/article/details/116026730)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [springboot整合mybatis-plus,代码自动生成](https://blog.csdn.net/qq_32784303/article/details/82964168)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值