excel导入数据库

需求

使用easyUi上传excel文件,并将excel里的数据存入数据库。

工具

Spring+SpringMVC+MyBatis,easyUi
(实验是在taotao商城的后台管理项目(源码即百度即可)的基础上实现的)

实现

easyUi实现界面

<form id="upExcelForm"  method="post" enctype="multipart/form-data">
   选择文件: <input id="uploadExcel" name="uploadExcel" class="easyui-filebox" style="width:200px" data-options="prompt:'请选择文件...'">
         <a href="#" class="easyui-linkbutton" style="width:122px" onclick="uploadExcel()" >导入</a>        
</form> 
<script type="text/javascript">
function uploadExcel(){
     //得到上传文件的全路径
     var fileName= $('#uploadExcel').filebox('getValue');
     var d1=/\.[^\.]+$/.exec(fileName);
     if(d1==".xls") {
      document.getElementById("upExcelForm").action="/item/upexcel";  
         document.getElementById("upExcelForm").submit();  
         $.messager.alert('提示','我已经上传了','info');
     }

}
</script>

ExcelUtil.java

public static <T> List<T> excelToList(InputStream in,
            Class<T> entityClass, LinkedHashMap<String, String> fieldMap,
            String[] uniqueFields) throws ExcelException {

        // 定义要返回的list
        List<T> resultList = new ArrayList<T>();

        try {

            // 根据Excel数据源创建WorkBook
            Workbook wb = Workbook.getWorkbook(in);
            // 获取工作表,
            //如果输入sheetName,则是根据sheet的名字来读取,我们的输入中直接使用第一个sheet表的数据,减少函数的变量
            Sheet sheet = wb.getSheet(0);

            // 获取工作表的有效行数
            int realRows = 0;
            for (int i = 0; i < sheet.getRows(); i++) {

                int nullCols = 0;
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell currentCell = sheet.getCell(j, i);
                    if (currentCell == null
                            || "".equals(currentCell.getContents().toString())) {
                        nullCols++;
                    }
                }

                if (nullCols == sheet.getColumns()) {
                    break;
                } else {
                    realRows++;
                }
            }

            // 如果Excel中没有数据则提示错误
            if (realRows <= 1) {
                throw new ExcelException("Excel文件中没有任何数据");
            }

            Cell[] firstRow = sheet.getRow(0);

            String[] excelFieldNames = new String[firstRow.length];

            // 获取Excel中的列名
            for (int i = 0; i < firstRow.length; i++) {
                excelFieldNames[i] = firstRow[i].getContents().toString()
                        .trim();
            }

            // 判断需要的字段在Excel中是否都存在
            boolean isExist = true;
            List<String> excelFieldList = Arrays.asList(excelFieldNames);
            for (String cnName : fieldMap.keySet()) {
                if (!excelFieldList.contains(cnName)) {
                    isExist = false;
                    break;
                }
            }

            // 如果有列名不存在,则抛出异常,提示错误
            if (!isExist) {
                throw new ExcelException("Excel中缺少必要的字段,或字段名称有误");
            }

            // 将列名和列号放入Map中,这样通过列名就可以拿到列号
            LinkedHashMap<String, Integer> colMap = new LinkedHashMap<String, Integer>();
            for (int i = 0; i < excelFieldNames.length; i++) {
                colMap.put(excelFieldNames[i], firstRow[i].getColumn());
            }

            // 判断是否有重复行
            // 1.获取uniqueFields指定的列
            Cell[][] uniqueCells = new Cell[uniqueFields.length][];
            for (int i = 0; i < uniqueFields.length; i++) {
                int col = colMap.get(uniqueFields[i]);
                uniqueCells[i] = sheet.getColumn(col);
            }

            // 2.从指定列中寻找重复行
            for (int i = 1; i < realRows; i++) {
                int nullCols = 0;
                for (int j = 0; j < uniqueFields.length; j++) {
                    String currentContent = uniqueCells[j][i].getContents();
                    Cell sameCell = sheet.findCell(currentContent,
                            uniqueCells[j][i].getColumn(),
                            uniqueCells[j][i].getRow() + 1,
                            uniqueCells[j][i].getColumn(),
                            uniqueCells[j][realRows - 1].getRow(), true);
                    if (sameCell != null) {
                        nullCols++;
                    }
                }

                if (nullCols == uniqueFields.length) {
                    throw new ExcelException("Excel中有重复行,请检查");
                }
            }

            // 将sheet转换为list
            for (int i = 1; i < realRows; i++) {
                // 新建要转换的对象
                T entity = entityClass.newInstance();

                // 给对象中的字段赋值
                for (Entry<String, String> entry : fieldMap.entrySet()) {
                    // 获取中文字段名
                    String cnNormalName = entry.getKey();
                    // 获取英文字段名
                    String enNormalName = entry.getValue();
                    // 根据中文字段名获取列号
                    int col = colMap.get(cnNormalName);

                    // 获取当前单元格中的内容
                    String content = sheet.getCell(col, i).getContents()
                            .toString().trim();

                    // 给对象赋值
                    setFieldValueByName(enNormalName, content, entity);
                }

                resultList.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 如果是ExcelException,则直接抛出
            if (e instanceof ExcelException) {
                throw (ExcelException) e;

                // 否则将其它异常包装成ExcelException再抛出
            } else {
                e.printStackTrace();
                throw new ExcelException("导入Excel失败");
            }
        }
        return resultList;
    }

ExcelUtil代码是在jxl.jar包的基础上实现的。在github上也有很多这样的工具函数,这也是我在网上找的,去掉了一个函数参数,(源代码来自:http://blog.csdn.net/zwk626542417/article/details/43153005
代码里面需要的ExcelException.java

public class ExcelException extends Exception {

    private static final long serialVersionUID = 7582457389069996252L;

    public ExcelException() {
    }

    public ExcelException(String message) {
        super(message);
    }

    public ExcelException(String message, Throwable cause) {
        super(message, cause);
    }

    public ExcelException(Throwable cause) {
        super(cause);
    }

    public ExcelException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

ssm部分代码实现

  • TbUserMapper.xml编写
<insert id="insertList" parameterType="java.util.List">
    insert into tb_user(username, password, phone, email, created, updated) values 
    <foreach collection="list" item="user" index="index" separator=",">
    <trim prefix=" (" suffix=")" suffixOverrides="," >
      <if test="user.id != null" >
        #{user.id,jdbcType=BIGINT},
      </if>
      <if test="user.username != null" >
        #{user.username,jdbcType=VARCHAR},
      </if>
      <if test="user.password != null" >
        #{user.password,jdbcType=VARCHAR},
      </if>
      <if test="user.phone != null" >
        #{user.phone,jdbcType=VARCHAR},
      </if>
      <if test="user.email != null" >
        #{user.email,jdbcType=VARCHAR},
      </if>
      <if test="user.created != null" >
        #{user.created,jdbcType=TIMESTAMP},
      </if>
      <if test="user.updated != null" >
        #{user.updated,jdbcType=TIMESTAMP},
      </if>
    </trim>
    </foreach>
  </insert>
  • TbUserMapper.java实现
int insertList(List<TbUser> record);
  • 接口ItemService.java
void insertUserList(List<TbUser> users);
  • 在ItemServiceImpl.java中实现该接口
    public void insertUserList(List<TbUser> users) {
        // TODO Auto-generated method stub
        userMapper.insertList(users);
    }
  • controller中调用
    @RequestMapping(value="/item/upexcel", method=RequestMethod.POST)
    @ResponseBody
    private void uploadExcel(@RequestParam("uploadExcel")CommonsMultipartFile uploadExcel, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream in = uploadExcel.getInputStream(); 
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<String, String>();
//      fieldMap.put("id", "id");
        fieldMap.put("username", "username");
        fieldMap.put("password", "password");
        fieldMap.put("phone", "phone");
        fieldMap.put("email", "email");
        fieldMap.put("created", "created");
        fieldMap.put("updated", "updated");
        String[] uniqueNames = new String[1];
        uniqueNames[0] = "username";
        List<TbUser> users = new ArrayList<TbUser>();
        try {
             users = ExcelUtil2.excelToList(in, TbUser.class, fieldMap, uniqueNames);
        } catch (ExcelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        itemService.insertUserList(users);
//      itemService.insertUsers(users);
//      return users;
    }

功能演示

管理界面导入111.xls,(jxl.jar貌似不支持.xlsx格式的表格,测试的时候没成功。只支持03版的)这里写图片描述
到数据库去查看:
这里写图片描述
至此功能算是完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如题,项目要用到jeasyui,所以必须要下载它的demo,获取相应的js,css等等的文件 jeasyui的下载地址:http://www.jeasyui.com/download/index.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <link href="easyui/themes/default/easyui.css" rel="stylesheet" type="text/css" /> <link href="easyui/themes/icon.css" rel="stylesheet" type="text/css" /> <link href="easyui/demo.css" rel="stylesheet" type="text/css" /> <script src="easyui/jquery.min.js" type="text/javascript"></script> <script src="easyui/jquery.easyui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#tab").datagrid({ // width: 600, //宽度 height: 400, //高度 singleSelect: true, //选中一行的设置 fitColumns:true, url: "EditorUserHandler.ashx", //请求路径 title: "用户信息", //标题 iconCls: "icon-add", //图标 // collapsible: true, //隐藏按钮 //冻结列 // frozenColumns: [[{ field: "chk", "checkbox": true}]], //复选框 //列 rownumbers: false, //传输参数 queryParams: { "action": "query" }, pagination: true, toolbar: "#tool" }); $("#tab").datagrid('getPager').pagination({ beforePageText: "第", afterPageText: "页", displayMsg: "当前 {from} - {to}条数据 共{total} 条数据", pageSize: 10, pageList: [5, 10, 15, 20, 30] }); }) </script> <!--//打印--> <script type="text/javascript"> function CreateFormPage(strPrintName, printDatagrid) { var tableString = '<div><table width="100%"><tr style="text-align:center;"><td colspan="2" style="font-size:24px; font-weight:bold;"><span style="text-decoration:underline;"> </span>年<span style="text-decoration:underline;"> </span>半年广东省房屋市政工程安全生产文明施工示范工地申报项目汇总表</td></tr><tr><td style="text-align:left;">地区(部门)公 章: </td><td style="text-align:right;">报送时间: 年 月 日</td></tr></table> <table cellspacing="0" class="pb">'; var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象 var columns = printDatagrid.datagrid("options").columns; // 得到columns对象 var nameList = ''; // 载入title if (typeof columns != 'undefined' && columns != '') { $(columns).each(function (index) { tableString += '\n<tr>'; if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') { for (var i = 0; i < frozenColumns[index].length; ++i) { if (!frozenColumns[index][i].hidden) { tableString += '\n<th width="' + frozenColumns[index][i].width + '"'; if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) { tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"'; } if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) { tableString += ' colspan="' + frozenColumns[index][i].colspan + '"'; } if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') { nameList += ',{"f":"' + frozenColumns[index][i].field + '", "a":"' + frozenColumns[index][i].align + '"}'; } tableString += '>' + frozenColumns[0][i].title + '</th>'; } } } for (var i = 0; i < columns[index].length; ++i) { if (!columns[index][i].hidden) { tableString += '\n<th width="' + columns[index][i].width + '"'; if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) { tableString += ' rowspan="' + columns[index][i].rowspan + '"'; } if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) { tableString += ' colspan="' + columns[index][i].colspan + '"'; } if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') { nameList += ',{"f":"' + columns[index][i].field + '", "a":"' + columns[index][i].align + '"}'; } tableString += '>' + columns[index][i].title + '</th>'; } } tableString += '\n</tr>'; }); } // 载入内容 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行 var nl = eval('([' + nameList.substring(1) + '])'); for (var i = 0; i < rows.length; ++i) { tableString += '\n<tr>'; $(nl).each(function (j) { var e = nl[j].f.lastIndexOf('_0'); tableString += '\n<td'; if (nl[j].a != 'undefined' && nl[j].a != '') { tableString += ' style="text-align:' + nl[j].a + ';"'; } tableString += '>'; if (e + 2 == nl[j].f.length) { tableString += rows[i][nl[j].f.substring(0, e)]; } else tableString += rows[i][nl[j].f]; tableString += '</td>'; }); tableString += '\n</tr>'; } tableString += '\n</table></div>'; window.showModalDialog("/print.htm", tableString, "location:No;status:No;help:No;dialogWidth:800px;dialogHeight:600px;scroll:auto;"); } </script> <!--//导出--> <script type="text/javascript"> function ChangeToTable(printDatagrid) { var tableString = '<table cellspacing="0" class="pb">'; var frozenColumns = printDatagrid.datagrid("options").frozenColumns; // 得到frozenColumns对象 var columns = printDatagrid.datagrid("options").columns; // 得到columns对象 var nameList = new Array(); // 载入title if (typeof columns != 'undefined' && columns != '') { $(columns).each(function (index) { tableString += '\n<tr>'; if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') { for (var i = 0; i < frozenColumns[index].length; ++i) { if (!frozenColumns[index][i].hidden) { tableString += '\n<th width="' + frozenColumns[index][i].width + '"'; if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) { tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"'; } if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) { tableString += ' colspan="' + frozenColumns[index][i].colspan + '"'; } if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') { nameList.push(frozenColumns[index][i]); } tableString += '>' + frozenColumns[0][i].title + '</th>'; } } } for (var i = 0; i < columns[index].length; ++i) { if (!columns[index][i].hidden) { tableString += '\n<th width="' + columns[index][i].width + '"'; if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) { tableString += ' rowspan="' + columns[index][i].rowspan + '"'; } if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) { tableString += ' colspan="' + columns[index][i].colspan + '"'; } if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') { nameList.push(columns[index][i]); } tableString += '>' + columns[index][i].title + '</th>'; } } tableString += '\n</tr>'; }); } // 载入内容 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行 for (var i = 0; i < rows.length; ++i) { tableString += '\n<tr>'; for (var j = 0; j < nameList.length; ++j) { var e = nameList[j].field.lastIndexOf('_0'); tableString += '\n<td'; if (nameList[j].align != 'undefined' && nameList[j].align != '') { tableString += ' style="text-align:' + nameList[j].align + ';"'; } tableString += '>'; if (e + 2 == nameList[j].field.length) { tableString += rows[i][nameList[j].field.substring(0, e)]; } else tableString += rows[i][nameList[j].field]; tableString += '</td>'; } tableString += '\n</tr>'; } tableString += '\n</table>'; return tableString; } function Export(strXlsName, exportGrid) { var f = $('<form action="export.aspx" method="post" id="fm1"></form>'); var i = $('<input type="hidden" id="txtContent" name="txtContent" />'); var l = $('<input type="hidden" id="txtName" name="txtName" />'); i.val(ChangeToTable(exportGrid)); i.appendTo(f); l.val(strXlsName); l.appendTo(f); f.appendTo(document.body).submit(); try { document.body.removeChild(f); } catch (e) { } } </script> </head> <body> <a href="javascript:void(0);" onclick="CreateFormPage('打印测试', $('#tab'));">打印</a> <a href="javascript:void(0);" onclick="Export('导出excel', $('#tab'));">导出</a> <table id="tab"> <thead> <tr> <th data-options="field:'flid',width:80" rowspan="2">编号</th> <th data-options="field:'flname',width:100" rowspan="2">姓名</th> <th colspan="3">详细信息</th> <th colspan="2">登录信息</th> </tr> <tr> <th data-options="field:'fladdress',width:80,align:'right'">地址</th> <th data-options="field:'flphone',width:80,align:'right'">电话</th> <th data-options="field:'flemail',width:240">邮箱</th> <th data-options="field:'flloginname',width:60,align:'center'">登录名</th> <th data-options="field:'flloginpwd',width:60,align:'center'">密码</th> </tr> </thead></table> <div id="tool"> <table border="0" cellspacing="0" cellpadding="0" width="100%" class="easyui-datagrid"> <!--<tr> <td style=" padding-left:2px"> <a href="#" class="easyui-linkbutton" id="id_add" iconcls="icon-add" plain="true" onclick="add_dg();" >添加</a> <a href="#" class="easyui-linkbutton" id="id_edit" iconCls="icon-edit" plain="true" onclick="edit_dg();">修改</a> <a href="#" class="easyui-linkbutton" id="id_cancel " onclick="delete_dg();" iconcls="icon-cancel" plain="true">删除</a> </td> </tr>--> </table> </div> <br /> <div id="dd_dg" style=" display:none"> <form id="fm_dg"> 编号:<input id="flid" name="flid" class="easyui-numberbox" type="text" required="true" missingMessage="请输入编号" /> <br /> 姓名:<input id="flname" name="flname" class="easyui-validatebox" required="true" missingMessage="请输入姓名"/> <br /> 地址:<input id="fladdress" name="fladdress" class="easyui-validatebox" type="text" required="true" missingMessage="请输入地址" /> <br /> 电话:<input id="flphone" name="flphone" class="easyui-validatebox" type="text" required="true" missingMessage="请输入电话" /> <br /> 邮箱:<input id="flMail" name="flMail" class="easyui-validatebox" type="text" validType="email" required="true" missingMessage="请输入邮箱" /> <br /> 登录名:<input id="flloginname" name="flloginname" class="easyui-validatebox" type="text" required="true" missingMessage="请输入登录名" /> <br /> 密码:<input type="password" id="flloginpwd" name="flloginpwd" class="easyui-validatebox" required="true" missingMessage="请输入密码" /> <br /> </form> </div> </body> </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值