解决如何使用layui导入Excel表数据

解决如何使用layui导入Excel表数据

1.前端页面html代码展示

 <button type="button" lay-submit="" class="layui-btn layui-btn-warm" lay-  filter="uploadImg">
      <i class="layui-icon"></i>导出Excel
 </button>

2.前端页面js代码展示

 layui.use(['table', 'form', 'layer', 'vip_table',"element", "laypage", "upload"],    function () {

        // 操作对象
        var form = layui.form
                , table = layui.table
                , layer = layui.layer
                , vipTable = layui.vip_table
                , $ = layui.jquery;
                var element = layui.element;
                var laypage = layui.laypage;
                var upload = layui.upload;//主要是这个
                
          
         //导入excel表
         //选完文件后不自动上传
         upload.render({
	           elem: '#importData'
	           ,url: '${pageContext.request.contextPath }/infoSheet/ajaxUpload'
	           ,auto: true
	           ,accept: 'file' //普通文件
	           //,multiple: true
	          // ,bindAction: '#test19'
	           ,done: function(res){
	               console.log(res)
	               //上传完毕
	               //如果上传失败
	               if(res.code > 0){
	                   return layer.msg("导入失败",{icon:5,time:1000});
	               }
	               //上传成功
	               return layer.msg("导入成功",{icon:6,time:1000});
	           }
	       });
     });          

3.java后台代码

//导入excel
    @ResponseBody
    @RequestMapping(value="/ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
    public Map<String, Object> ajaxUploadExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
     System.out.println("进来了");
        Map<String, Object> map = new HashMap<String, Object>();
        String aa= infoSheetService.ajaxUploadExcel(file, request, response);
        if("success".equals(aa))
        {
        	
        map.put("code", 0);
        map.put("msg", "success");
        }
        else {
        	map.put("code", 1);
            map.put("msg", "fail");
        }
        return map;
    }

    /*
     * 文件导入(批量导入)
     * */
   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));
            InfoSheet vo = new InfoSheet();
            InfoSheet j = null;

            try {
            	HashMap<Object, Object> map=new HashMap<Object, Object>();
            	map.put("infoName", String.valueOf(lo.get(0)));
                j = infoSheetMapper.selectByPrimaryKey1(map);
            } catch (NumberFormatException e) {
                System.out.println("没有新增");
                return "fail";
            }
           // vo.setInfoId(Integer.valueOf(String.valueOf(lo.get(0))));//企业ID
            vo.setInfoName(String.valueOf(lo.get(0)));//企业名称
              // IndustryType industryType =new IndustryType();
              // industryType.setIndustryTypeId(Integer.valueOf(String.valueOf(lo.get(2))));
         //   System.out.println(i+"String.valueOf(lo.get(1))===="+String.valueOf(lo.get(1)));
            
            IndustryType industryType=industryTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(1)));
           //如果行业的类型不存在,添加新的行业类型
            if(industryType==null)
            {   IndustryType industryType0=new IndustryType();
            	industryType0.setIndustryTypeName(String.valueOf(lo.get(1)));
            	industryTypeMapper.insert(industryType0);
            	IndustryType industryType1=industryTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(1)));
            	vo.setIndustryType(industryType1);//行业类型ID
            }else {
            	 vo.setIndustryType(industryType);//行业类型ID
			}
           
            
              //InfoType infoType=new InfoType();
              // infoType.setInfoTypeId(Integer.valueOf(String.valueOf(lo.get(3))));
            InfoType infoType =infoTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(2)));
            if (infoType==null) {
            	InfoType infoType0 =new InfoType();
				infoType0.setInfoTypeName(String.valueOf(lo.get(2)));
				infoTypeMapper.insert(infoType0);
				 InfoType infoType1 =infoTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(2)));
				 vo.setInfoType(infoType1);//企业类型ID 
			} else {
				 vo.setInfoType(infoType);//企业类型ID
			}
            
           
            Area area=areaMapper.selectByPrimaryKey1(String.valueOf(lo.get(3)));//公司地区
            if (area==null) {
            	Area area0=new Area();
				area0.setAreaName(String.valueOf(lo.get(3)));
            	areaMapper.insert(area0);
            	Area area1=areaMapper.selectByPrimaryKey1(String.valueOf(lo.get(3)));//公司地区
            	vo.setArea(area1);
			} else {
				vo.setArea(area);
			}
            
            vo.setInfoGround(String.valueOf(lo.get(4)));//详细所属地
           vo.setRegistCapital(String.valueOf(lo.get(5)));//资本注册
            
            vo.setInfoPhone(String.valueOf(lo.get(6)));//联系电话
           vo.setInfoPostbox(String.valueOf(lo.get(7)));//公司邮箱
           
			
			  Date infoTime; 
			  try { 
				  String  infoString=String.valueOf(lo.get(8)).replace(".", "-");
			 //System.out.println("infoString====="+infoString); // 
				  if("20114-04-14".equals(infoString))
				  {
					  System.out.println("i================"+i);
				  }
				  String  info=infoString+" 00:00:00";
			 infoTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(info);
			//成立时间
			 vo.setInfoTime(infoTime);
			  } catch (ParseException e) { 
                      e.printStackTrace(); 
			 }
		
            if(j == null)
            {
               // System.out.println("判断j为空的话");
                infoSheetMapper.insert(vo);
            }
            else
            {
            //    System.out.println("判断j为不空的话");
            	infoSheetMapper.updateByPrimaryKey(vo);
            }
        }
        return "success";
    }




package com.tools;

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;

//ajaxUploadExcel方法中的业务逻辑需要调用的ExcelUtils类的方法
public class ExcelUtils {

    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述:获取IO流中的数据,组装成List>对象
     * @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;
    }


}
package com.pojo;

import java.util.Date;
//导入的实体类
public class InfoSheet {
    /**
     * info_sheet
     */
    private Integer infoId;

    /**
     * 行业类型
     */
    private IndustryType industryType;

    /**
     * 企业类型
     */
    private InfoType infoType;

    /**
     * info_sheet
     */
    private String infoName;

    /**
     * info_sheet
     */
    private String infoGround;

    /**
     * info_sheet
     */
    private String registCapital;

    /**
     * info_sheet
     */
    private String infoPhone;

    /**
     * info_sheet
     */
    private String infoPostbox;

    /**
     * info_sheet
     */
    private Date infoTime;

    /**
     * 企业ID
     * @return info_ID 企业ID
     *
     * @mbggenerated 2019-06-26
     */
    public Integer getInfoId() {
        return infoId;
    }
    
    private Area area;
    
    public Area getArea() {
		return area;
	}

	public void setArea(Area area) {
		this.area = area;
	}

	
    /**
     * 企业ID
     * @param infoId 企业ID
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoId(Integer infoId) {
        this.infoId = infoId;
    }

    
    /**
     * 行业类型
     *
     * @mbggenerated 2019-06-26
     */
    public IndustryType getIndustryType() {
		return industryType;
	}

	public void setIndustryType(IndustryType industryType) {
		this.industryType = industryType;
	}
	 /**
     * 企业类型ID
     *
     * @mbggenerated 2019-06-26
     */
	public InfoType getInfoType() {
		return infoType;
	}

	public void setInfoType(InfoType infoType) {
		this.infoType = infoType;
	}
	
	/**
     * 企业名称
     * @return info_name 企业名称
     *
     * @mbggenerated 2019-06-26
     */
    public String getInfoName() {
        return infoName;
    }

    

	/**
     * 企业名称
     * @param infoName 企业名称
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoName(String infoName) {
        this.infoName = infoName;
    }

    /**
     * 详细所属地
     * @return info_ground 详细所属地
     *
     * @mbggenerated 2019-06-26
     */
    public String getInfoGround() {
        return infoGround;
    }

    /**
     * 详细所属地
     * @param infoGround 详细所属地
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoGround(String infoGround) {
        this.infoGround = infoGround;
    }

    /**
     * 资本注册
     * @return regist_capital 资本注册
     *
     * @mbggenerated 2019-06-26
     */
    public String getRegistCapital() {
        return registCapital;
    }

    /**
     * 资本注册
     * @param registCapital 资本注册
     *
     * @mbggenerated 2019-06-26
     */
    public void setRegistCapital(String registCapital) {
        this.registCapital = registCapital;
    }

    /**
     * 联系电话
     * @return info_phone 联系电话
     *
     * @mbggenerated 2019-06-26
     */
    public String getInfoPhone() {
        return infoPhone;
    }

    /**
     * 联系电话
     * @param infoPhone 联系电话
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoPhone(String infoPhone) {
        this.infoPhone = infoPhone;
    }

    /**
     * 公司邮箱
     * @return info_postbox 公司邮箱
     *
     * @mbggenerated 2019-06-26
     */
    public String getInfoPostbox() {
        return infoPostbox;
    }

    /**
     * 公司邮箱
     * @param infoPostbox 公司邮箱
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoPostbox(String infoPostbox) {
        this.infoPostbox = infoPostbox;
    }

    /**
     * 成立时间
     * @return info_time 成立时间
     *
     * @mbggenerated 2019-06-26
     */
    public Date getInfoTime() {
        return infoTime;
    }

    /**
     * 成立时间
     * @param infoTime 成立时间
     *
     * @mbggenerated 2019-06-26
     */
    public void setInfoTime(Date infoTime) {
        this.infoTime = infoTime;
    }
}

4.感谢你的浏览访问

  工作几年,略有心得,然很少整理成文,平常工作中浏览了不少道友的好文章,受益良多。 
  顾也开始写一些文章, 希望能与各位道友分享进步 !!!!
  如果有用,欢迎各位点赞评论,若有不足,亦可指正!!!

你可能感兴趣的:(功能插件,java,excel,css)