SSM+Layui实现批量导入数据功能

SSM+Layui实现批量导入数据功能
最近要实现批量导入功能,查看了相关资料,以及百度了相关内容,发现有点不是很全,特别是引入的依赖不全
话不多说,直接上代码开始:
1、pom.xml文件引入相关依赖

 <!--文件上传依赖-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.14-beta1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.14-beta1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.14-beta1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>

2、编写一个工具类-----------ExcelUtils.java:


import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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;


public class ExcelUtils {

    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 IOException
     */
    public  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = this.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(); 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(this.getValue(cell));
                }
                list.add(li);
            }
        }

        return list;

    }

    /**
     * 描述:根据文件后缀,自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public  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
     */
    //解决excel类型问题,获得数值
    public  String getValue(Cell cell) {
        String value = "";
        if(null==cell){
            return value;
        }
        switch (cell.getCellType()) {
            //数值型
            case Cell.CELL_TYPE_NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ,获取该cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    value = format.format(date);;
                }else {// 纯数字
                    BigDecimal big=new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if(null!=value&&!"".equals(value.trim())){
                        String[] item = value.split("[.]");
                        if(1<item.length&&"0".equals(item[1])){
                            value=item[0];
                        }
                    }
                }
                break;
            //字符串类型
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue().toString();
                break;
            // 公式类型
            case Cell.CELL_TYPE_FORMULA:
                //读公式计算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
                    value = cell.getStringCellValue().toString();
                }
                break;
            // 布尔类型
            case Cell.CELL_TYPE_BOOLEAN:
                value = " "+ cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue().toString();
        }
        if("null".endsWith(value.trim())){
            value="";
        }
        return value;
    }


}

3、后台---------控制类

    @ResponseBody
    @RequestMapping(value="/ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
    public Map<String, String> ajaxUploadExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
    //    System.out.println("进来了");
        Map<String, String> map = new HashMap<>();
        studentService.ajaxUploadExcel(file, request, response);
        map.put("msg", "ok");
        return map;
    }

4.1、实现类(业务层)1--------StudentServiceImpl.java
注:本方法是 不判断数据表中是否有相同的数据,直接插入,默认设置主键ID为null,下面还有一个是查询数据表看是否有相同的数据,然后根据主键修改其内容。可以根据需求选取其中一种

/*
     * 文件导入(批量导入)
     * */
    @Override
    public String ajaxUploadExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        /*MultipartFile file = multipartRequest.getFile("file");*/

     //   System.out.println("得到数据文件");
        if(file.isEmpty()){
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in =null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
     //   System.out.println("加载流");
        List<List<Object>> listob = null;
        try {
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
        //    System.out.println("listob,zize是:"+listob.size());
            List<Object> lo = listob.get(i);
        //    System.out.println("遍历" + listob.get(i));
            Student vo = new Student();
       //     Student j = null;

       //     System.out.println("lo.size是:"+lo.size());

            if(lo.size() == 5){    //无ID这一列
           //     System.out.println("无ID");
                vo.setStudentName(String.valueOf(lo.get(0)));
                vo.setStudentNumber(String.valueOf(lo.get(1)));
                vo.setClassroom(String.valueOf(lo.get(2)));
                vo.setPosition(String.valueOf(lo.get(3)));
                vo.setGradeId(Integer.valueOf(String.valueOf(lo.get(4))));
            }else if(lo.size() == 6){   //有ID这一列
          //      System.out.println("有ID");
                vo.setStudentName(String.valueOf(lo.get(1)));
                vo.setStudentNumber(String.valueOf(lo.get(2)));
                vo.setClassroom(String.valueOf(lo.get(3)));
                vo.setPosition(String.valueOf(lo.get(4)));
                vo.setGradeId(Integer.valueOf(String.valueOf(lo.get(5))));
            }

          //  System.out.println("vo是: "+vo.toString());

            studentMapper.addStudent(vo);

        }
        return "success";
    }

4.2、实现类(业务层)2--------StudentServiceImpl.java

/*
     * 文件导入(批量导入)
     * */
    @Override
    public String ajaxUploadExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        if(file.isEmpty()){
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in =null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<List<Object>> listob = null;
        try {
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
            List<Object> lo = listob.get(i);
   //         System.out.println("遍历" + listob.get(i));
            Student vo = new Student();
            Student j = null;

            try {
                j = studentMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
            } catch (NumberFormatException e) {
                System.out.println("没有新增");
            }

            vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
            vo.setStudentName(String.valueOf(lo.get(1)));
            vo.setStudentNumber(String.valueOf(lo.get(2)));
            vo.setClassroom(String.valueOf(lo.get(3)));
            vo.setPosition(String.valueOf(lo.get(4)));
            vo.setGradeId(Integer.valueOf(String.valueOf(lo.get(5))));
      //      System.out.println("这个开始");
      //      System.out.println(vo.toString());
      //      System.out.println("这个结束");
            if(j == null)
            {
               // System.out.println("判断j为空的话");
                studentMapper.addStudent(vo);
            }
            else
            {
            //    System.out.println("判断j为不空的话");
                studentMapper.updateById(vo);
            }
        }
        return "success";
    }

5、数据库表结构
数据表结构
6、前端js

<script>
    layui.use('upload', function(){
        var $ = layui.jquery
            ,upload = layui.upload;

        //选完文件后不自动上传
        upload.render({
            elem: '#test8'
            ,url: '${ctx}/excelUpload/ajaxUpload'
            ,auto: false
            ,accept: 'file' //普通文件
            //,multiple: true
            ,bindAction: '#test19'
            ,done: function(res){
                console.log(res)
                //上传完毕
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('导入失败');
                }
                //上传成功
                return layer.msg('导入成功');
            }
        });
    });
</script>

7、前端效果展示
在这里插入图片描述如果有需要,可以在这一个页面加上一个下载导入模板的功能,方便客户导入!!! 这样就大大的避免的导入出错的几率

最后说明:这个只实现数据批量导入的功能,大家看了我的代码,发现基本没有做异常处理,如果需要做异常处理,本人可以建议使用log4j+spring AOP实现异常处理。本人现在也处于初学阶段,没有深入研究,不喜勿喷,谢谢!!!
如有不对或者哪里可以优化等等,欢迎大家指出,谢谢!

配套资源代码链接:SSM+Layui实现数据导入源码

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页