Commit 2c042e77 by fengshuonan

添加excel导入导出

parent 547cc437
......@@ -160,6 +160,13 @@
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
<!--excel导入导出-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.0.0</version>
</dependency>
<!--需要分布式session的话需要放开注释-->
<!--<dependency>-->
<!--<groupId>org.springframework.session</groupId>-->
......
package cn.stylefeng.guns.modular.excel;
import cn.afterturn.easypoi.entity.vo.MapExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.demos.ExcelItem;
import cn.stylefeng.guns.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* excel导入导出示例
*
* @author fengshuonan
* @Date 2019/3/9 11:03
*/
@Controller
@RequestMapping("/excel")
public class ExcelController {
@Autowired
private UserService userService;
@Autowired
private GunsProperties gunsProperties;
/**
* excel导入页面
*
* @author fengshuonan
* @Date 2019/3/9 11:03
*/
@RequestMapping("/import")
public String importIndex() {
return "/modular/demos/excel_import.html";
}
/**
* 上传excel填报
*/
@RequestMapping("/uploadExcel")
@ResponseBody
public ResponseData uploadExcel(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
String name = file.getOriginalFilename();
request.getSession().setAttribute("upFile", name);
String fileSavePath = gunsProperties.getFileUploadPath();
try {
file.transferTo(new File(fileSavePath + name));
} catch (Exception e) {
throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
}
HashMap<String, Object> map = new HashMap<>();
map.put("fileId", IdWorker.getIdStr());
return ResponseData.success(0, "上传成功", map);
}
/**
* 获取上传成功的数据
*/
@RequestMapping("/getUploadData")
@ResponseBody
public Object getUploadData(HttpServletRequest request) {
String name = (String) request.getSession().getAttribute("upFile");
String fileSavePath = gunsProperties.getFileUploadPath();
if (name != null) {
File file = new File(fileSavePath + name);
try {
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
List result = ExcelImportUtil.importExcel(file, ExcelItem.class, params);
LayuiPageInfo returns = new LayuiPageInfo();
returns.setCount(result.size());
returns.setData(result);
return returns;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* excel导出
*
* @author fengshuonan
* @Date 2019/3/9 11:03
*/
@RequestMapping("/export")
public void export(ModelMap modelMap, HttpServletRequest request,
HttpServletResponse response) {
//初始化表头
List<ExcelExportEntity> entity = new ArrayList<>();
entity.add(new ExcelExportEntity("用户id", "USER_ID"));
entity.add(new ExcelExportEntity("头像", "AVATAR"));
entity.add(new ExcelExportEntity("账号", "ACCOUNT"));
entity.add(new ExcelExportEntity("姓名", "NAME"));
entity.add(new ExcelExportEntity("生日", "BIRTHDAY"));
entity.add(new ExcelExportEntity("性别", "SEX"));
entity.add(new ExcelExportEntity("邮箱", "EMAIL"));
entity.add(new ExcelExportEntity("电话", "PHONE"));
entity.add(new ExcelExportEntity("角色id", "ROLE_ID"));
entity.add(new ExcelExportEntity("部门id", "DEPT_ID"));
entity.add(new ExcelExportEntity("状态", "STATUS"));
entity.add(new ExcelExportEntity("创建时间", "CREATE_TIME"));
//初始化化数据
List<Map<String, Object>> maps = userService.listMaps();
ArrayList<Map<String, Object>> total = new ArrayList<>();
for (int i = 0; i < 100; i++) {
total.addAll(maps);
}
ExportParams params = new ExportParams("Guns管理系统所有用户", "用户表", ExcelType.XSSF);
modelMap.put(MapExcelConstants.MAP_LIST, total);
modelMap.put(MapExcelConstants.ENTITY_LIST, entity);
modelMap.put(MapExcelConstants.PARAMS, params);
modelMap.put(MapExcelConstants.FILE_NAME, "Guns管理系统所有用户");
PoiBaseView.render(modelMap, request, response, MapExcelConstants.EASYPOI_MAP_EXCEL_VIEW);
}
}
package cn.stylefeng.guns.modular.demos;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 管理员表
* </p>
*
* @author stylefeng
* @since 2018-12-07
*/
@TableName("sys_user")
@Data
public class ExcelItem implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "USER_ID", type = IdType.ID_WORKER)
@Excel(name = "用户id")
private Long userId;
/**
* 头像
*/
@TableField("AVATAR")
@Excel(name = "头像")
private String avatar;
/**
* 账号
*/
@TableField("ACCOUNT")
@Excel(name = "账号")
private String account;
/**
* 密码
*/
@TableField("PASSWORD")
private String password;
/**
* md5密码盐
*/
@TableField("SALT")
private String salt;
/**
* 名字
*/
@TableField("NAME")
@Excel(name = "姓名")
private String name;
/**
* 生日
*/
@Excel(name = "生日")
@TableField("BIRTHDAY")
private Date birthday;
/**
* 性别(字典)
*/
@TableField("SEX")
@Excel(name = "性别")
private String sex;
/**
* 电子邮件
*/
@TableField("EMAIL")
@Excel(name = "邮箱")
private String email;
/**
* 电话
*/
@TableField("PHONE")
@Excel(name = "电话")
private String phone;
/**
* 角色id(多个逗号隔开)
*/
@TableField("ROLE_ID")
@Excel(name = "角色id")
private String roleId;
/**
* 部门id(多个逗号隔开)
*/
@TableField("DEPT_ID")
@Excel(name = "部门id")
private Long deptId;
/**
* 状态(字典)
*/
@TableField("STATUS")
@Excel(name = "状态")
private String status;
/**
* 创建时间
*/
@TableField(value = "CREATE_TIME", fill = FieldFill.INSERT)
@Excel(name = "创建时间")
private Date createTime;
/**
* 创建人
*/
@TableField(value = "CREATE_USER", fill = FieldFill.INSERT)
private Long createUser;
/**
* 更新时间
*/
@TableField(value = "UPDATE_TIME", fill = FieldFill.UPDATE)
private Date updateTime;
/**
* 更新人
*/
@TableField(value = "UPDATE_USER", fill = FieldFill.UPDATE)
private Long updateUser;
/**
* 乐观锁
*/
@TableField("VERSION")
private Integer version;
}
layui.use(['layer', 'form', 'table', 'ztree', 'laydate', 'admin', 'ax','upload'], function () {
var layer = layui.layer;
var form = layui.form;
var table = layui.table;
var $ZTree = layui.ztree;
var $ax = layui.ax;
var laydate = layui.laydate;
var admin = layui.admin;
var upload = layui.upload;
/**
* 系统管理--用户管理
*/
var MgrUser = {
tableId: "userTable", //表格id
condition: {
name: "",
deptId: "",
timeLimit: ""
}
};
/**
* 初始化表格的列
*/
MgrUser.initColumn = function () {
return [[
{type: 'checkbox'},
{field: 'userId', hide: true, sort: true, title: '用户id'},
{field: 'account', sort: true, title: '账号'},
{field: 'name', sort: true, title: '姓名'},
{field: 'sexName', sort: true, title: '性别'},
{field: 'roleName', sort: true, title: '角色'},
{field: 'deptName', sort: true, title: '部门'},
{field: 'email', sort: true, title: '邮箱'},
{field: 'phone', sort: true, title: '电话'},
{field: 'createTime', sort: true, title: '创建时间'},
{field: 'status', sort: true, templet: '#statusTpl', title: '状态'}
]];
};
/**
* 选择部门时
*/
MgrUser.onClickDept = function (e, treeId, treeNode) {
MgrUser.condition.deptId = treeNode.id;
MgrUser.search();
};
/**
* 点击查询按钮
*/
MgrUser.search = function () {
var queryData = {};
queryData['deptId'] = MgrUser.condition.deptId;
queryData['name'] = $("#name").val();
queryData['timeLimit'] = $("#timeLimit").val();
table.reload(MgrUser.tableId, {where: queryData});
};
/**
* 弹出添加用户对话框
*/
MgrUser.openAddUser = function () {
admin.putTempData('formOk', false);
top.layui.admin.open({
type: 2,
title: '添加用户',
content: Feng.ctxPath + '/mgr/user_add',
end: function () {
admin.getTempData('formOk') && table.reload(MgrUser.tableId);
}
});
};
/**
* 导出excel按钮
*/
MgrUser.exportExcel = function () {
var checkRows = table.checkStatus(MgrUser.tableId);
if (checkRows.data.length === 0) {
Feng.error("请选择要导出的数据");
} else {
table.exportFile(tableResult.config.id, checkRows.data, 'xls');
}
};
/**
* 点击编辑用户按钮时
*
* @param data 点击按钮时候的行数据
*/
MgrUser.onEditUser = function (data) {
admin.putTempData('formOk', false);
top.layui.admin.open({
type: 2,
title: '编辑用户',
content: Feng.ctxPath + '/mgr/user_edit?userId=' + data.userId,
end: function () {
admin.getTempData('formOk') && table.reload(MgrUser.tableId);
}
});
};
/**
* 点击删除用户按钮
*
* @param data 点击按钮时候的行数据
*/
MgrUser.onDeleteUser = function (data) {
var operation = function () {
var ajax = new $ax(Feng.ctxPath + "/mgr/delete", function () {
table.reload(MgrUser.tableId);
Feng.success("删除成功!");
}, function (data) {
Feng.error("删除失败!" + data.responseJSON.message + "!");
});
ajax.set("userId", data.userId);
ajax.start();
};
Feng.confirm("是否删除用户" + data.account + "?", operation);
};
/**
* 分配角色
*
* @param data 点击按钮时候的行数据
*/
MgrUser.roleAssign = function (data) {
layer.open({
type: 2,
title: '角色分配',
area: ['300px', '400px'],
content: Feng.ctxPath + '/mgr/role_assign?userId=' + data.userId,
end: function () {
table.reload(MgrUser.tableId);
}
});
};
/**
* 重置密码
*
* @param data 点击按钮时候的行数据
*/
MgrUser.resetPassword = function (data) {
Feng.confirm("是否重置密码为111111 ?", function () {
var ajax = new $ax(Feng.ctxPath + "/mgr/reset", function (data) {
Feng.success("重置密码成功!");
}, function (data) {
Feng.error("重置密码失败!");
});
ajax.set("userId", data.userId);
ajax.start();
});
};
/**
* 修改用户状态
*
* @param userId 用户id
* @param checked 是否选中(true,false),选中就是解锁用户,未选中就是锁定用户
*/
MgrUser.changeUserStatus = function (userId, checked) {
if (checked) {
var ajax = new $ax(Feng.ctxPath + "/mgr/unfreeze", function (data) {
Feng.success("解除冻结成功!");
}, function (data) {
Feng.error("解除冻结失败!");
table.reload(MgrUser.tableId);
});
ajax.set("userId", userId);
ajax.start();
} else {
var ajax = new $ax(Feng.ctxPath + "/mgr/freeze", function (data) {
Feng.success("冻结成功!");
}, function (data) {
Feng.error("冻结失败!" + data.responseJSON.message + "!");
table.reload(MgrUser.tableId);
});
ajax.set("userId", userId);
ajax.start();
}
};
// 渲染表格
var tableResult = table.render({
elem: '#' + MgrUser.tableId,
url: Feng.ctxPath + '/mgr/list',
page: true,
height: "full-158",
cellMinWidth: 100,
cols: MgrUser.initColumn()
});
//渲染时间选择框
laydate.render({
elem: '#timeLimit',
range: true,
max: Feng.currentDate()
});
//初始化左侧部门树
var ztree = new $ZTree("deptTree", "/dept/tree");
ztree.bindOnClick(MgrUser.onClickDept);
ztree.init();
// 搜索按钮点击事件
$('#btnSearch').click(function () {
MgrUser.search();
});
// 添加按钮点击事件
$('#btnAdd').click(function () {
MgrUser.openAddUser();
});
//执行实例
var uploadInst = upload.render({
elem: '#btnExp'
, url: '/excel/uploadExcel'
,accept: 'file'
, done: function (res) {
table.reload(MgrUser.tableId, {url: Feng.ctxPath + "/excel/getUploadData"});
}
, error: function () {
//请求异常回调
}
});
// 工具条点击事件
table.on('tool(' + MgrUser.tableId + ')', function (obj) {
var data = obj.data;
var layEvent = obj.event;
if (layEvent === 'edit') {
MgrUser.onEditUser(data);
} else if (layEvent === 'delete') {
MgrUser.onDeleteUser(data);
} else if (layEvent === 'roleAssign') {
MgrUser.roleAssign(data);
} else if (layEvent === 'reset') {
MgrUser.resetPassword(data);
}
});
// 修改user状态
form.on('switch(status)', function (obj) {
var userId = obj.elem.value;
var checked = obj.elem.checked ? true : false;
MgrUser.changeUserStatus(userId, checked);
});
});
@layout("/common/_container.html",{plugins:["ztree"],js:["/assets/modular/demos/excel_import.js"]}){
<div class="layui-body-header">
<span class="layui-body-header-title">用户管理</span>
</div>
<div class="layui-fluid">
<div class="layui-row layui-col-space15">
<div class="layui-col-sm12">
<div class="layui-card">
<div class="layui-card-body">
<div class="layui-form toolbar">
<div class="layui-form-item">
<div class="layui-inline">
<button id="btnExp" class="layui-btn icon-btn">
<i class="layui-icon">&#xe67c;</i>导入excel并展示
</button>
</div>
</div>
</div>
<table class="layui-table" id="userTable" lay-filter="userTable"></table>
</div>
</div>
</div>
</div>
</div>
<script type="text/html" id="statusTpl">
<input type="checkbox" lay-filter="status" value="{{d.userId}}" lay-skin="switch" lay-text="正常|冻结" {{d.status=='ENABLE'?'checked':''}} />
</script>
@}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment