springboot整合easyExcel导入导出,并操作mysql数据库

1、所需部分jar包: 

 
     com.alibaba
     easyexcel
     1.1.2-beat1


     com.baomidou
     mybatis-plus-boot-starter
     3.1.2


    com.alibaba
    fastjson
    1.2.59

2、代码段(部分代码,是从我springcloud练习项目中拿出来)

(1)控制层:这里需要注意的是,需要将你需要service接口当做参数传入saxReadListStringV2007()中否则在easyExcel的监听器中,你无法进行数据库操作。直接在监听器中用@autowrid或者@resource注解,无法将service接口注入其中;

package com.lucifer.demo.controller;

import com.lucifer.common.utils.CommonResult;
import com.lucifer.demo.aspect.NoRepeatSubmit;
import com.lucifer.demo.pojo.Order;
import com.lucifer.demo.pojo.OrderDemo;
import com.lucifer.demo.service.OrderService;
import com.lucifer.demo.service.impl.OrderServiceImpl;
import com.lucifer.demo.util.excel.ExportExcelUtils;
import com.lucifer.demo.util.excel.ImportExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author: lucifer
 * @date: 2019/8/28
 * @description:
 */
@Slf4j
@RefreshScope
@RestController
public class TestController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderServiceImpl orderServiceImpl;

    @PostMapping(value = "testImportExcel")
    public CommonResult> testImportExcel(HttpServletRequest httpServletRequest) throws IOException {
        long startTime = System.currentTimeMillis();
        ImportExcelUtils.saxReadListStringV2007(httpServletRequest,orderServiceImpl);
        long endTime = System.currentTimeMillis();
        log.info("耗时:{}",(endTime-startTime)/1000);
        return CommonResult.success(null);
    }

    @GetMapping(value = "testExportExcel")
    public CommonResult> testExportExcel() throws IOException {
        List orders = orderService.orderQueryAll();
        ExportExcelUtils.writeV2007(orders, Order.class);
        return CommonResult.success(null);
    }

    @NoRepeatSubmit
    @GetMapping(value = "selectOrders")
    public CommonResult> selectOrders(){
        List orders = orderService.orderQueryAll();
        return CommonResult.success(orders);
    }

    @PostMapping("insertOrder")
    public CommonResult insertOrder(@RequestBody OrderDemo order){
        Integer id=orderService.insertOrder(order);
        return CommonResult.success(id);
    }
}

 (2)Excel导入:

package com.lucifer.demo.util.excel;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lucifer.demo.pojo.Order;
import com.lucifer.demo.service.OrderService;
import com.lucifer.demo.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author: lucifer
 * @date: 2019/8/28
 * @description: 导入Excel工具类
 */
@Slf4j
public class ImportExcelUtils {


    /**
     * 07版本excel读数据量大于1千行,内部采用回调方法.
     *
     * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流
     */
    public static void saxReadListStringV2007(HttpServletRequest request, OrderServiceImpl orderServiceImpl) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile requestFile = multipartRequest.getFile("file");
        String originalFilename = requestFile.getOriginalFilename();
        if (!originalFilename.endsWith(ExcelTypeEnum.XLS.getValue()) && !originalFilename.endsWith(ExcelTypeEnum.XLSX.getValue())) {
            log.error("Excel导入错误文件名称:{}", originalFilename);
            throw new RuntimeException("不是Excel格式文件");
        }
        InputStream inputStream = null;
        try {
            inputStream = requestFile.getInputStream();
            if (inputStream == null) {
                return;
            }
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            AnalysisEventListener excelListener = new ExcelListener(orderServiceImpl);
            EasyExcelFactory.readBySax(bufferedInputStream, new Sheet(1, 1, Order.class), excelListener);
        } finally {
            inputStream.close();
        }
    }


}

(3)easyExcel监听器;在其中执行你的数据库操作;

package com.lucifer.demo.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lucifer.demo.pojo.OrderDemo;
import com.lucifer.demo.service.OrderService;
import com.lucifer.demo.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @author: lucifer
 * @date: 2019/8/28
 * @description: 解析监听器
 * 每解析一行会回调invoke()方法。
 * 整个excel解析结束会执行doAfterAllAnalysed()方法
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener {

    private OrderServiceImpl orderServiceImpl;

    public ExcelListener(OrderServiceImpl orderServiceImpl) {
        super();
        this.orderServiceImpl = orderServiceImpl;
    }

    private List  data = new ArrayList<>();

    @Override
    public void invoke(Object object, AnalysisContext context) {
        System.out.println(context.getCurrentSheet());
        data.add(object);
        if(data.size()>=100){
            doSomething();
            data.clear();
            //data = new ArrayList<>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        doSomething();
    }

    public void doSomething(){
        List list=new ArrayList<>();
        for (Object o:data) {
            String jsonString = JSONObject.toJSONString(o);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            OrderDemo OrderDemo = JSON.toJavaObject(jsonObject, OrderDemo.class);
            list.add(OrderDemo);
        }
        orderServiceImpl.saveBatch(list);
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }
} 
  

(4)业务接口; 

package com.lucifer.demo.service;

import com.lucifer.demo.pojo.Order;
import com.lucifer.demo.pojo.OrderDemo;

import java.util.List;

/**
 * @author Lucifer
 */
public interface OrderService {


    /**
     * 查询所有订单
     *
     * @return
     */
    List orderQueryAll();

    /**
     * 新增订单
     *
     * @param order
     * @return
     */
    Integer insertOrder(OrderDemo order);

}

(5)实现类; 

package com.lucifer.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lucifer.demo.dao.OrderDemoMapper;
import com.lucifer.demo.pojo.Order;
import com.lucifer.demo.pojo.OrderDemo;
import com.lucifer.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: lucifer
 * @date: 2019/8/30
 * @description:
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl implements OrderService {

    @Resource
    private OrderDemoMapper OrderDemoMapper;


    @Override
    public List orderQueryAll() {
        return OrderDemoMapper.selectAll();
    }

    @Override
    public Integer insertOrder(OrderDemo order) {
        return OrderDemoMapper.insert(order);
    }

}

关于easyExcel导入导出重要代码就这么多了,其它代码就不粘贴其中了;

 

你可能感兴趣的:(SpringBoot技术篇,Java常见问题)