jeesite匯入excel表格做法
阿新 • • 發佈:2018-11-12
1、利用程式碼生成功能製作好單表增刪改查的模組
2、修改前段程式碼,插入‘匯入’按鈕並且寫好匯入彈出框介面,加入複製貼上使用者模組的前段程式碼
3、修改實體類,加上註釋
4、在控制器加入下載模板和匯入功能的響應方法
第一步:根據前面兩篇博文去操作,建立左樹右表的單表增刪改查,在原有的根據欄位查詢資料的查詢按鈕右邊,加入匯入按鈕
第二步:修改前段程式碼,如下:
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
<title>課程表管理</title>
<meta name="decorator" content="default" />
<script type="text/javascript">
$(document).ready(function() {
$("#btnImport").click(function(){
$.jBox($("#importBox").html(), {title:"匯入資料", buttons:{"關閉":true },
bottomText:"匯入檔案不能超過5M,僅允許匯入“xls”或“xlsx”格式檔案!"});
});
});
function page(n, s) {
$("#pageNo").val(n);
$("#pageSize").val(s);
$("#searchForm").submit();
return false;
}
</script>
</head>
<body>
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/jsl/jslCourse/import"
method="post" enctype="multipart/form-data" class="form-search"
style="padding-left: 20px; text-align: center;"
onsubmit="loading('正在匯入,請稍等...');">
<br />
<input id="uploadFile" name="file" type="file"
style="width: 330px" />
<br /> <br />
<input id="btnImportSubmit"
class="btn btn-primary" type="submit" value=" 導 入 " /> <a
href="${ctx}/jsl/jslCourse/import/template">下載模板</a>
</form>
</div>
<ul class="nav nav-tabs">
<li class="active"><a href="${ctx}/jsl/jslCourse/">課程表列表</a></li>
<shiro:hasPermission name="jsl:jslCourse:edit">
<li><a href="${ctx}/jsl/jslCourse/form">課程表新增</a></li>
</shiro:hasPermission>
</ul>
<form:form id="searchForm" modelAttribute="jslCourse"
action="${ctx}/jsl/jslCourse/" method="post"
class="breadcrumb form-search">
<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}" />
<input id="pageSize" name="pageSize" type="hidden"
value="${page.pageSize}" />
<ul class="ul-form">
<li><label>上課教室:</label> <form:input path="classroom"
htmlEscape="false" maxlength="64" class="input-medium" /></li>
<li><label>任課老師:</label> <form:input path="courseteacher"
htmlEscape="false" maxlength="64" class="input-medium" /></li>
<li class="btns"><input id="btnSubmit" class="btn btn-primary"
type="submit" value="查詢" /></li>
<li class="btns"><input id="btnImport" class="btn btn-primary"
type="button" value="匯入" /></li>
<li class="clearfix"></li>
</ul>
</form:form>
<sys:message content="${message}" />
<table id="contentTable"
class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>歸屬公司</th>
<th>歸屬部門</th>
<th>課程名稱</th>
<th>上課教室</th>
<th>聽課老師</th>
<th>任課老師</th>
<th>專業班級</th>
<th>聽課時間</th>
<th>更新時間</th>
<th>備註資訊</th>
<shiro:hasPermission name="jsl:jslCourse:edit">
<th>操作</th>
</shiro:hasPermission>
</tr>
</thead>
<tbody>
<c:forEach items="${page.list}" var="jslCourse">
<tr>
<td><a href="${ctx}/jsl/jslCourse/form?id=${jslCourse.id}">
${jslCourse.company.name} </a></td>
<td>${jslCourse.office.name}</td>
<td>${jslCourse.coursename}</td>
<td>${jslCourse.classroom}</td>
<td>${jslCourse.listenteacher}</td>
<td>${jslCourse.courseteacher}</td>
<td>${jslCourse.professionalclass}</td>
<td><fmt:formatDate value="${jslCourse.coursetime}"
pattern="yyyy-MM-dd HH:mm:ss" /></td>
<td><fmt:formatDate value="${jslCourse.updateDate}"
pattern="yyyy-MM-dd HH:mm:ss" /></td>
<td>${jslCourse.remarks}</td>
<shiro:hasPermission name="jsl:jslCourse:edit">
<td><a href="${ctx}/jsl/jslCourse/form?id=${jslCourse.id}">修改</a>
<a href="${ctx}/jsl/jslCourse/delete?id=${jslCourse.id}"
onclick="return confirmx('確認要刪除該課程表嗎?', this.href)">刪除</a></td>
</shiro:hasPermission>
</tr>
</c:forEach>
</tbody>
</table>
<div class="pagination">${page}</div>
</body>
</html>
第三步:實體類中凡是要通過excel匯入的欄位都需要在實體類的欄位的get()方法添加註釋
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.jsl.entity;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.thinkgem.jeesite.common.persistence.DataEntity;
import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
/**
* 課程表管理Entity
* @author jsl
* @version 2017-10-21
*/
public class JslCourse extends DataEntity<JslCourse> {
private static final long serialVersionUID = 1L;
private Office company; // 歸屬公司
private Office office; // 歸屬部門
private String coursename; // 課程名稱
private String classroom; // 上課教室
private String listenteacher; //聽課老師
private String courseteacher; // 任課老師
private String professionalclass; // 專業班級
private Date coursetime; // 聽課時間
public JslCourse() {
super();
}
public JslCourse(String id){
super(id);
}
@JsonIgnore
@NotNull(message="歸屬公司不能為空")
@ExcelField(title="歸屬公司", align=2, sort=20)
public Office getCompany() {
return company;
}
public void setCompany(Office company) {
this.company = company;
}
@JsonIgnore
@NotNull(message="歸屬部門不能為空")
@ExcelField(title="歸屬部門", align=2, sort=25)
public Office getOffice() {
return office;
}
public void setOffice(Office office) {
this.office = office;
}
@Length(min=0, max=64, message="課程名長度必須介於 1 和 64之間")
@ExcelField(title="課程名", align=2, sort=30)
public String getCoursename() {
return coursename;
}
public void setCoursename(String coursename) {
this.coursename = coursename;
}
@ExcelField(title="課室", align=2, sort=35)
@Length(min=0, max=64, message="上課教室長度必須介於 0 和 64 之間")
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
@ExcelField(title="聽課老師", align=2, sort=40)
@Length(min=0, max=64, message="聽課老師長度必須介於 0 和 64 之間")
public String getListenteacher() {
return listenteacher;
}
public void setListenteacher(String listenteacher) {
this.listenteacher = listenteacher;
}
@ExcelField(title="任課老師", align=2, sort=45)
@Length(min=0, max=64, message="任課老師長度必須介於 0 和 64 之間")
public String getCourseteacher() {
return courseteacher;
}
public void setCourseteacher(String courseteacher) {
this.courseteacher = courseteacher;
}
@ExcelField(title="專業班級", align=2, sort=50)
@Length(min=0, max=64, message="專業班級長度必須介於 0 和 64 之間")
public String getProfessionalclass() {
return professionalclass;
}
public void setProfessionalclass(String professionalclass) {
this.professionalclass = professionalclass;
}
@ExcelField(title="聽課時間", align=2, sort=55)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCoursetime() {
return coursetime;
}
public void setCoursetime(Date coursetime) {
this.coursetime = coursetime;
}
}
第四步:在控制層新增響應匯入按鈕的操作,主要有兩個部分,一個是下載模板、一個是匯入響應
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.jsl.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.jsl.entity.JslCourse;
import com.thinkgem.jeesite.modules.jsl.service.JslCourseService;
/**
* 課程表管理Controller
* @author jsl
* @version 2017-10-21
*/
@Controller
@RequestMapping(value = "${adminPath}/jsl/jslCourse")
public class JslCourseController extends BaseController {
@Autowired
private JslCourseService jslCourseService;
@ModelAttribute
public JslCourse get(@RequestParam(required=false) String id) {
JslCourse entity = null;
if (StringUtils.isNotBlank(id)){
entity = jslCourseService.get(id);
}
if (entity == null){
entity = new JslCourse();
}
return entity;
}
@RequiresPermissions("jsl:jslCourse:view")
@RequestMapping(value = {"index"})
public String index(JslCourse jslCourse, Model model) {
return "modules/jsl/jslCourseIndex";
}
@RequiresPermissions("jsl:jslCourse:edit")
@RequestMapping(value = "import", method=RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes){
try {
int successNum=0;
int failureNum=0;
StringBuilder failureMsg=new StringBuilder();
ImportExcel ei=new ImportExcel(file, 1, 0);
List<JslCourse> list=ei.getDataList(JslCourse.class);
for(JslCourse jslCourse:list){
try {
jslCourseService.save(jslCourse);
successNum++;
addMessage(redirectAttributes, "已成功匯入 "+successNum+" 條使用者"+failureMsg);
} catch (ConstraintViolationException ex) {
failureMsg.append("<br/>課程名 "+jslCourse.getCoursename()+" 匯入失敗:");
List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
for (String message : messageList){
failureMsg.append(message+"; ");
failureNum++;
}
}catch (Exception ex) {
failureMsg.append("<br/>課程名 "+jslCourse.getCoursename()+" 匯入失敗:"+ex.getMessage());
}
}
if (failureNum>0){
failureMsg.insert(0, ",失敗 "+failureNum+" 條使用者,匯入資訊如下:");
}
addMessage(redirectAttributes, "已成功匯入 "+successNum+" 條課程"+failureMsg);
} catch (Exception e) {
addMessage(redirectAttributes, "匯入課程表失敗!失敗資訊:"+e.getMessage());
}
return "redirect:" + adminPath + "/jsl/jslCourse?repage";
}
/**
* 下載匯入課程表資料模板
* @param response
* @param redirectAttributes
* @return
*/
@RequiresPermissions("jsl:jslCourse:view")
@RequestMapping(value = "import/template")
public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = "課程表資料匯入模板.xlsx";
List<JslCourse> list = Lists.newArrayList(); list.add(new JslCourse());
new ExportExcel("課程表資料", JslCourse.class, 2).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "匯入模板下載失敗!失敗資訊:"+e.getMessage());
}
return "redirect:" + adminPath + "/jsl/jslCourse?repage";
}
@RequiresPermissions("jsl:jslCourse:view")
@RequestMapping(value = {"list", ""})
public String list(JslCourse jslCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<JslCourse> page = jslCourseService.findPage(new Page<JslCourse>(request, response), jslCourse);
model.addAttribute("page", page);
return "modules/jsl/jslCourseList";
}
@RequiresPermissions("jsl:jslCourse:view")
@RequestMapping(value = "form")
public String form(JslCourse jslCourse, Model model) {
model.addAttribute("jslCourse", jslCourse);
return "modules/jsl/jslCourseForm";
}
@RequiresPermissions("jsl:jslCourse:edit")
@RequestMapping(value = "save")
public String save(JslCourse jslCourse, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, jslCourse)){
return form(jslCourse, model);
}
jslCourseService.save(jslCourse);
addMessage(redirectAttributes, "儲存課程表成功");
return "redirect:"+Global.getAdminPath()+"/jsl/jslCourse/?repage";
}
@RequiresPermissions("jsl:jslCourse:edit")
@RequestMapping(value = "delete")
public String delete(JslCourse jslCourse, RedirectAttributes redirectAttributes) {
jslCourseService.delete(jslCourse);
addMessage(redirectAttributes, "刪除課程表成功");
return "redirect:"+Global.getAdminPath()+"/jsl/jslCourse/?repage";
}
}