Hutool是一个小而全的Java工具类库,通过静态方法封装。Hutool官方链接
使用方法:
UserContrller中添加一个导出接口
/*导出接口*/
@GetMapping("/export")
public void export(HttpServletResponse response) throws Exception{
//从数据库查询出所有数据,如果需要获取其他的数据,就调用其他的方法
List<User> list=userService.list();
//通过工具类创建write 写出磁盘路径
//ExcelWriter writer= ExcelUtil.getWriter(filesUpLoadPth + "/用户信息.xlsx");
//这里的参数也可以设置绝对路径,本项目实现网页的下载,省略下载路径
ExcelWriter writer= ExcelUtil.getWriter(true);
writer.addHeaderAlias("username","用户名");//用别名的方法,实现Excel文件的标题是中文的
writer.addHeaderAlias("password","密码");
writer.addHeaderAlias("nickname","昵称");
writer.addHeaderAlias("email","邮箱");
writer.addHeaderAlias("phone","电话");
writer.addHeaderAlias("address","地址");
writer.addHeaderAlias("created_time","创建时间");
//一次性写出list内部的对象到excel,强制输出标题
writer.write(list,true);
String filename= URLEncoder.encode("用户信息","UTF-8");
//设置浏览器弹出响应格式,输出xlsx格式,官网也可以查看输出xls格式的方法
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+ filename+".xlsx");
ServletOutputStream out=response.getOutputStream();
writer.flush(out, true);
out.close();
writer.close();
}
vue2.0 前端代码
<el-button type="primary" @click="exp">导出<i class="el-icon-top"></i></el-button>
methods方法为:
exp(){
window.open("http://localhost:8084/user/export");
},
导入
<el-upload
action="http://localhost:8080/user/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
<el-button type="primary" style="margin-left:5px">导入<i class="el-icon-bottom"></i> </el-button>
</el-upload>
handleExcelImportSuccess(){ //实现导入
this.$message.success("导入成功");
this.load();
},
controller
@PostMapping("/import")
public void importExcel(MultipartFile file) throws IOException {
//1.第一种 头必须和实体(英文)一样
//文件处理成io流
InputStream in = file.getInputStream();
// //io流给ExcelReader
ExcelReader excelReader=ExcelUtil.getReader(in);
// //读取数据且转化为list
// List<User> list = excelReader.readAll(User.class);
//2.第二种导入方式
//忽略第一行头(第一行是中文的情况),直接读取表的内容
List<List<Object>> list = excelReader.read(1);
List<UserEntity> listUser = CollUtil.newArrayList();
for (List<Object> row: list) {
UserEntity user=new UserEntity();
user.setUsername(row.get(0).toString());
user.setPassword(row.get(1).toString());
user.setNickname(row.get(2).toString());
user.setNickname(row.get(3).toString());
user.setPhone(row.get(4).toString());
user.setAddress(row.get(5).toString());
listUser.add(user);
// ****类似一一对应****
}
//批量注册进数据库
userService.saveBatch(listUser);
}