spring 导入excel

来源:互联网 发布:太原培训网络 编辑:程序博客网 时间:2024/05/16 12:27

1、页面

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->    <meta name="description" content="">    <meta name="author" content="">    <link rel="icon" th:href="@{/static/images/favicon.ico}">    <title>用户管理</title>    <!-- Bootstrap core CSS -->    <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}">    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->    <link th:href="@{/static/css/ie10-viewport-bug-workaround.css}" rel="stylesheet">    <!-- Custom styles for this template -->    <link th:href="@{/static/css/index.css}" rel="stylesheet">    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->    <!--[if lt IE 9]><!--<script src="../js/ie8-responsive-file-warning.js"></script>--><![endif]-->    <script th:src="@{/static/js/ie-emulation-modes-warning.js}"></script>    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->    <!--[if lt IE 9]>    <!--<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>-->    <!--<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>-->    <![endif]--></head><body><nav th:replace="common/fragment :: nav-header"></nav><div class="container-fluid">    <div class="row">        <nav th:replace="common/fragment :: nav-menu"></nav>        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">            <h2 class="page-header">题库中心</h2>            <!--<h2 class="sub-header">Section title</h2>-->            <div class="table-responsive">                <button type="button" class="btn btn-default import">导入</button>                <form id="uploadForm" enctype="multipart/form-data" method="post">                    <input id="upfile" type="file" name="upfile" style="display: none">                </form>                <table class="table table-striped">                    <thead>                    <tr>                        <th class="text-center">#</th>                        <th class="text-center">帐号</th>                        <th class="text-center">姓名</th>                        <th class="text-center">性别</th>                        <th class="text-center">生日</th>                        <th class="text-center">电话</th>                        <th class="text-center">微信</th>                        <th class="text-center">QQ</th>                        <th class="text-center">邮箱</th>                        <th class="text-center">操作</th>                    </tr>                    </thead>                    <tbody>                    <!--<tr class="text-center" th:each="customer:${page.content}">-->                        <!--<td>-->                            <!--<label>-->                                <!--<input type="checkbox" value="remember-me">-->                            <!--</label>-->                        <!--</td>-->                        <!--<td th:text="${customer.accountNumber}">zhangsan</td>-->                        <!--<td th:text="${customer.adminName}">张三</td>-->                        <!--<td th:text="${customer.sex?.name}">男</td>-->                        <!--<td th:text="${customer.birth}">1990-03-05</td>-->                        <!--<td th:text="${customer.phone}">15135173514</td>-->                        <!--<td th:text="${customer.weixin}">123456</td>-->                        <!--<td th:text="${customer.qqNumber}">643971065</td>-->                        <!--<td th:text="${customer.email}">15135173514@163.com</td>-->                        <!--<td>-->                            <!--<a class="btn btn-sm btn-success">查看</a>-->                            <!--<a class="btn btn-sm btn-success">修改</a>-->                            <!--<a class="btn btn-sm btn-danger">删除</a>-->                        <!--</td>-->                    <!--</tr>-->                    </tbody>                </table>            </div>        </div>    </div></div><!-- Bootstrap core JavaScript================================================== --><!-- Placed at the end of the document so the pages load faster --><!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>--><script th:src="@{/static/js/jquery.min.js}"></script><script th:src="@{/static/js/bootstrap.min.js}"></script><!-- Just to make our placeholder images work. Don't actually copy the next line! --><script th:src="@{/static/js/holder.min.js}"></script><!-- IE10 viewport hack for Surface/desktop Windows 8 bug --><script th:src="@{/static/js/ie10-viewport-bug-workaround.js}"></script><script th:src="@{/static/js/global.js}"></script><script th:src="@{/static/js/jquery.form.js}"></script><script type="text/javascript" th:inline="javascript">    var ctx = /*[[@{/}]]*/;    //导入excel    $(".import").bind("click",function (e) {        $(this).next().find("input[type='file']").trigger("click").unbind("change").bind("change",function () {            if (!this.value) return;            if(checkData()){                $(this).parent().ajaxSubmit({                    url: ctx + "importExcel",                    type: "post",                    beforeSend: function() {                        console.log("准备上传");                    },                    success:function (result) {                        if (result.success){                            alert("上传成功");                        }else{                            alert(result.message);                        }                    }, error: function(error) {                        alert("出错啦");                    }                })            }        })    })    //JS校验form表单信息    function checkData(){        var fileDir = $("#upfile").val();        var suffix = fileDir.substr(fileDir.lastIndexOf("."));        console.log(suffix);        if("" == fileDir){            alert("选择需要导入的Excel文件!");            return false;        }        if(".XLS" != suffix && ".XLSX" != suffix && ".xls" != suffix && ".xlsx" != suffix){            alert("选择Excel格式的文件导入!");            return false;        }        return true;    }</script></body></html>

2、conreoller


package com.shanglan.exam.controller;import com.shanglan.exam.base.AjaxResponse;import com.shanglan.exam.service.ExamService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Pageable;import org.springframework.data.web.PageableDefault;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import java.io.InputStream;/** * Created by cuishiying on 2017/6/13. */@RestController@RequestMapping("/")public class IndexController {    @Autowired    private ExamService examService;    @RequestMapping    public ModelAndView index(@PageableDefault Pageable pageable){        ModelAndView model = new ModelAndView("question_bank");        return model;    }    @RequestMapping(path = "/importExcel", method = RequestMethod.POST)    public AjaxResponse<?> importExcel(HttpServletRequest request) throws Exception{        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;        MultipartFile file = multipartRequest.getFile("upfile");        if(file.isEmpty()){            throw new Exception("文件不存在!");        }        InputStream in = file.getInputStream();        AjaxResponse ajaxResponse = examService.importExcel(in, file);        return ajaxResponse;    }}


3、service


package com.shanglan.exam.service;import com.shanglan.exam.base.AjaxResponse;import com.shanglan.exam.base.ExcelUtils;import com.shanglan.exam.entity.Question;import com.shanglan.exam.repository.ExamRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;import java.util.ArrayList;import java.util.List;/** * Created by cuishiying on 2017/6/13. */@Service@Transactionalpublic class ExamService {    @Autowired    private ExamRepository examRepository;    public AjaxResponse importExcel(InputStream in, MultipartFile file) throws Exception {        List<List<Object>> listob = ExcelUtils.getBankListByExcel(in,file.getOriginalFilename());        List<Question> questions=new ArrayList<Question>();        for (int i = 0; i < listob.size(); i++) {            List<Object> lo = listob.get(i);            Question question = new Question();            question.setTitle(String.valueOf(lo.get(0)));            question.setScore(Integer.parseInt(String.valueOf(lo.get(1))));            questions.add(question);        }        examRepository.save(questions);        return AjaxResponse.success();    }}


4、respository

package com.shanglan.exam.repository;import com.shanglan.exam.entity.Question;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;/** * Created by cuishiying on 2017/6/13. */public interface ExamRepository extends JpaRepository<Question, Integer>,JpaSpecificationExecutor<Question> {}