java导入excel模板中的数据到数据库

一、前台页面其实就是一个文件的上传的模板

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/include/init.jsp"%>
<c:set var="now" value="<%=new java.util.Date()%>" />
<html>
<head>
<title>批量导入被调查人员信息</title>
<link rel="stylesheet" type="text/css" href="${ctx}/plugins/jquery-easyui/themes/default/easyui.css" />
<link rel="stylesheet" type="text/css" href="${ctx}/plugins/jquery-easyui/themes/icon.css" />
<script type="text/javascript" src="${ctx}/plugins/form/jquery.form.js"></script>
<script language="javascript" type="text/javascript" src="${ctx}/plugins/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="${ctx}/plugins/jquery-easyui/jquery.easyui.min.js"></script>
<%@ include file="/common/include/common_rkSelect.jsp"%>
<script type="text/javascript" src="${ctx}/plugins/autocomplete/jquery.autocomplete.js"></script>
<link   rel="stylesheet" href="${ctx}/plugins/autocomplete/jquery.autocomplete.css"  /> 
<script src="<c:url value='/plugins/form/jquery.form.js' />"></script>
<script src="${ctx}/plugins/layer/layer.js"></script>
<script type="text/javascript">
	$(function(){
		$("#uploadEventBtn").unbind("click").bind("click", function() {
			$("#uploadEventFile").click();
		});
		$("#uploadEventFile").bind("change", function() {
			$("#uploadEventPath").attr("value",	$("#uploadEventFile").val());
		});
	})
	function save() {
		var uploadEventFile = $("#uploadEventFile").val();
		if (uploadEventFile == '') {
			alert("请择excel,再上传");
		} else if (uploadEventFile.lastIndexOf(".xls") < 0) {//可判断以.xls和.xlsx结尾的excel  
			alert("只能上传Excel文件");
		} 
		var formData = new FormData($('form')[0]);
		$.ajax({
			type:"POST",
			url:"<%=service_domain%>/satisfy/satbeExam/addbatch",
			data:formData,
			cache : false,
            contentType : false,
            processData : false,
			success:function(data){
				var result = data;
				var api = frameElement.api, w = api.opener;
				w.$.dialog.alert(result.message, function(){
					frameElement.api.opener.refresh();
				})
			},
			error:function(xhr,status,err){
				alert("error");
				console.log(err);
			}
		});
	}
</script>
</head>
<body>
<br />
 <div class="popWin_w">
 <form enctype="multipart/form-data" id="batchUpload"  action="" method="post" class="form-horizontal">  
 	<table class="table_s2">
 		<tr>
 			<td width="18%" align="center"> 
				Excel模板:
			</td>
			<td width="32%" align="left">
				<input type="file" name="file"  style="width:0px;height:0px;" id="uploadEventFile"/> 
				<input id="uploadEventPath"  disabled="disabled"  type="text" placeholder="请选择excel表" style="border: 1px solid #e6e6e6; height: 26px;width: 200px;" /> 
			</td>
			<td>
				<button class="btn btn-success btn-xs" id="uploadEventBtn" style="height:26px;"  type="button" >选择文件</button>  
			</td>
		</tr>
	</table>
</form>
	<div class="table_s2_btns">
		<button type="button" class="button_com hand_icon button_save orange_back" onClick="save();" style="margin-right: 20px;">
			<span><span><span class="ok">批量导入</span> </span> </span>
		</button>
	</div>
</div>
</body>
</html>

后台的controller

/**
	 * 批量导入
	 */
	@RequestMapping("/addbatch")
	@ApiOperation(value = "批量导入人员信息", httpMethod = "POST", 
	    consumes="application/json;charset=UFT-8",produces="application/json;charset=UFT-8",
	    notes = "批量导入人员信息")
	public Map<String, Object> addbatch(@ApiParam(name="file",value="文件",required=true) MultipartFile file){
		Map<String, Object> map = new HashMap<String, Object>();
        String result = manager.readExcelFile(file);  
        map.put("message", result);
        return map;  
	}

service层

@SuppressWarnings("unused")
	public String readExcelFile(MultipartFile file) {
		// TODO Auto-generated method stub
		String result = "";  
        //创建处理EXCEL的类  
        ReadExcel readExcel = new ReadExcel();  
        //解析excel,获取上传的事件单  
        List<Map<String, Object>> beExamList = readExcel.getExcelInfo(file);  
        //至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,  
        for(Map<String, Object> modal:beExamList){
        	SatBeExam entity = new SatBeExam();
        	entity.setCommunity((String)modal.get("community"));
        	entity.setName((String)modal.get("name"));
        	entity.setPhone((String)modal.get("phone"));
        	entity.setStreet((String)modal.get("street"));
        	entity.setDept_name((String)modal.get("dept_name"));
        	entity.setIdcard((String)modal.get("idcard"));
        	entity.setRemark((String)modal.get("remark"));
        	entity.setDept_id((String)modal.get("dept_id"));
        	if(entity != null){
        		dao.save(entity);
        		result = "插入数据库成功";
        	}else{
        		result = "插入数据库是失败";
        	}
        }
        return result;  
	}

dao层就不往出贴了

还有一个相当于工具的方法

package com.rockontrol.satisfy.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
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 org.springframework.web.multipart.MultipartFile;

public class ReadExcel {

	// 总行数
    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 fielName
     * @return
     */
    public List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 获取文件名
//        List<Map<String, Object>> userList = new LinkedList<Map<String, Object>>();
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            return createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据excel里面的内容读取客户信息
     * 
     * @param is      输入流
     * @param isExcel2003   excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            return readExcelValue(wb);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取Excel里面客户的信息
     * 
     * @param wb
     * @return
     */
    private List<Map<String, Object>> readExcelValue(Workbook wb) {
        // 得到第一个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<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        // 循环Excel行数
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            // 循环Excel的列
            Map<String, Object> map = new HashMap<String, Object>();
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {
                        // 如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String name = String.valueOf(cell.getNumericCellValue());
                            map.put("name", name.substring(0, name.length() - 2 > 0 ? name.length() - 2 : 1));// 名称
                        } else {
                            map.put("name", cell.getStringCellValue());// 名称
                        }
                    } else if (c == 1) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String dept_name = String.valueOf(cell.getNumericCellValue());
                            map.put("dept_name",dept_name.substring(0, dept_name.length() - 2 > 0 ? dept_name.length() - 2 : 1));// 
                        } else {
                            map.put("dept_name",cell.getStringCellValue());// 性别
                        }
                    } else if (c == 2) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String street = String.valueOf(cell.getNumericCellValue());
                            map.put("street", street.substring(0, street.length() - 2 > 0 ? street.length() - 2 : 1));// 
                        } else {
                            map.put("street", cell.getStringCellValue());// 
                        }
                    }else if(c == 3){
                    	if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String community = String.valueOf(cell.getNumericCellValue());
                            map.put("community", community.substring(0, community.length() - 2 > 0 ? community.length() - 2 : 1));// 
                        } else {
                            map.put("community", cell.getStringCellValue());// 
                        }
                    }else if(c == 4){
                    	if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String phone = String.valueOf(cell.getNumericCellValue());
                            map.put("phone", phone.substring(0, phone.length() - 2 > 0 ? phone.length() - 2 : 1));// 
                        } else {
                            map.put("phone", cell.getStringCellValue());// 
                        }
                    }else if(c == 5){
                    	if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String idcard = String.valueOf(cell.getNumericCellValue());
                            map.put("idcard", idcard.substring(0, idcard.length() - 2 > 0 ? idcard.length() - 2 : 1));// 
                        } else {
                            map.put("idcard", cell.getStringCellValue());// 
                        }
                    }else if(c == 6){
                    	if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                            String remark = String.valueOf(cell.getNumericCellValue());
                            map.put("remark", remark.substring(0, remark.length() - 2 > 0 ? remark.length() - 2 : 1));// 
                        } else {
                            map.put("remark", cell.getStringCellValue());// 
                        }
                    }
                }
            }
            // 添加到list
            userList.add(map);
        }
        return userList;
    }

    /**
     * 验证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)$");
    }
    
}

到此,导入完成。

excel模板如下

姓名行政区划街道社区电话身份证号备注
112223344556677
张三北京海淀大悟1111111222222233333
张三北京海淀大悟1111111222222233333
张三北京海淀大悟1111111222222233333
张三北京海淀大悟1111111222222233333
张三北京海淀大悟1111111222222233333
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值