Excel导入导出
在管理一个系统时,总会有许多的数据,为了方便浏览查看数据,系统总会提供「导出Excel」的功能;有导出就有导入,在要向数据库中插入大量的数据时,我们向程序提供准备好的 Excel,然后程序读取表格内容,并将数据添加到数据库中。实现这个「导入/导出 Excel」的功能也不复杂,我们使用第三方的类库即可实现。
比如: Apache poi、Java Excel(JXL)和阿里巴巴开源的 Easyexcel 等。
这么多类库该怎么选呢?在这里我给大家推荐阿里巴巴开源的「Easyexcel」。
MultipartFile工具类
- MultipartFile是SpringMVC提供简化上传操作的工具类。
- 在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类,非常麻烦。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
- 以下是MultipartFile工具类全部的接口方法。
方法名 | 返回值 | 作用 |
---|---|---|
getContentType() | String | 返回文件的内容类型 |
getlnputStream() | InputStream | 返回InputStream读取文件的内容 |
getName() | String | 返回参数的名称 |
getOriginalFilename() | String | 获取上传文件件的原名 |
getSize() | long | 返回文件大小 以字节为单位 |
isEmpty() | boolean | 判断是否为空,或者上传的文件是否有内容 |
transferTo(File dest) | void | 用来把 MultipartFile 转换换成 File,将数据保存到一个目标文件中 |
getBytes() | byte[] | 将文件内容转化成一个byte[] 返回 |
EasyExcel
Excel解析流程图:
EasyExcel读取Excel的解析原理:
排除模型中的属性字段
在数据模型的字段上加@ExcelIgnore注解排除
@ExcelIgnore
private String password;
复杂头数据写入
@ExcelProperty注解的value属性是一个数组类型, 设置多个head时会自动合并.
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class ComplexHeadUser {
@ExcelProperty(value = {"group1", "用户编号"}, index = 0)
private Integer userId;
@ExcelProperty(value = {"group1", "姓名"}, index = 1)
private String userName;
@ExcelProperty(value = {"group2", "入职时间"}, index = 2)
private Date hireDate;
// lombok 会生成getter/setter方法
}
日期/数字类型格式化
对于日期和数字,有时候需要对其展示的样式进行格式化, EasyExcel提供了以下注解
@DateTimeFormat 日期格式化
@NumberFormat 数字格式化(小数或百分数)
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class User {
@ExcelProperty(value = "用户编号", index = 0)
private Integer userId;
@ExcelProperty(value = "姓名", index = 1)
private String userName;
@ExcelProperty(value = "性别", index = 3)
private String gender;
@ExcelProperty(value = "工资", index = 4)
@NumberFormat(value = "###.#") // 数字格式化,保留1位小数
private Double salary;
@ExcelProperty(value = "入职时间", index = 2)
@DateTimeFormat(value = "yyyy年MM月dd日 HH时mm分ss秒") // 日期格式化
private Date hireDate;
// lombok 会生成getter/setter方法
}
设置写入Excel的列宽和行高
@HeadRowHeight(value = 30) // 头部行高
@ContentRowHeight(value = 25) // 内容行高
@ColumnWidth(value = 20) // 列宽, 可以作用在类或字段上
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@HeadRowHeight(value = 30) // 头部行高
@ContentRowHeight(value = 25) // 内容行高
@ColumnWidth(value = 20) // 列宽
public class WidthAndHeightData {
@ExcelProperty(value = "字符串标题")
private String string;
@ExcelProperty(value = "日期标题")
private Date date;
@ExcelProperty(value = "数字标题")
@ColumnWidth(value = 25)
private Double doubleData;
// lombok 会生成getter/setter方法
}
通过注解形式设置写入Excel样式
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@HeadRowHeight(value = 30) // 头部行高
@ContentRowHeight(value = 25) // 内容行高
@ColumnWidth(value = 20) // 列宽
// 头背景设置成红色 IndexedColors.RED.getIndex()
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 10)
// 头字体设置成20, 字体默认宋体
@HeadFontStyle(fontName = "宋体", fontHeightInPoints = 20)
// 内容的背景设置成绿色 IndexedColors.GREEN.getIndex()
@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 17)
// 内容字体设置成20, 字体默认宋体
@ContentFontStyle(fontName = "宋体", fontHeightInPoints = 20)
public class DemoStyleData {
// 字符串的头背景设置成粉红 IndexedColors.PINK.getIndex()
@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 14)
// 字符串的头字体设置成20
@HeadFontStyle(fontHeightInPoints = 30)
// 字符串的内容背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()
@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)
// 字符串的内容字体设置成20,默认宋体
@ContentFontStyle(fontName = "宋体", fontHeightInPoints = 20)
@ExcelProperty(value = "字符串标题")
private String string;
@ExcelProperty(value = "日期标题")
private Date date;
@ExcelProperty(value = "数字标题")
private Double doubleData;
// lombok 会生成getter/setter方法
}
合并单元格
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@HeadRowHeight(value = 25) // 头部行高
@ContentRowHeight(value = 20) // 内容行高
@ColumnWidth(value = 20) // 列宽
/**
* @OnceAbsoluteMerge 指定从哪一行/列开始,哪一行/列结束,进行单元格合并
* firstRowIndex 起始行索引,从0开始
* lastRowIndex 结束行索引
* firstColumnIndex 起始列索引,从0开始
* lastColumnIndex 结束列索引
*/
// 例如: 第2-3行,2-3列进行合并
@OnceAbsoluteMerge(firstRowIndex = 1, lastRowIndex = 2, firstColumnIndex = 1, lastColumnIndex = 2)
public class DemoMergeData {
// 每隔两行合并一次(竖着合并单元格)
// @ContentLoopMerge(eachRow = 2)
@ExcelProperty(value = "字符串标题")
private String string;
@ExcelProperty(value = "日期标题")
private Date date;
@ExcelProperty(value = "数字标题")
private Double doubleData;
// lombok 会生成getter/setter方法
}
数据转换器
在实际应用场景中, 我们系统db存储的数据可以是枚举, 在界面或导出到Excel文件需要展示为对于的枚举值形式.
比如: 性别, 状态等. EasyExcel提供了转换器接口Converter供我们使用, 我们只需要自定义转换器实现接口, 并将自定义转换器类型传入要转换的属性字段中. 以下面的性别gender字段为例:
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class UserModel {
@ExcelProperty(value = "用户编号", index = 0)
private Integer userId;
@ExcelProperty(value = "姓名", index = 1)
private String userName;
// 性别添加了转换器, db中存入的是integer类型的枚举 0 , 1 ,2
@ExcelProperty(value = "性别", index = 3, converter = GenderConverter.class)
private Integer gender;
@ExcelProperty(value = "工资", index = 4)
@NumberFormat(value = "###.#")
private Double salary;
@ExcelProperty(value = "入职时间", index = 2)
@DateTimeFormat(value = "yyyy年MM月dd日 HH时mm分ss秒")
private Date hireDate;
// lombok 会生成getter/setter方法
}
- 自定义转换器
/**
* 类描述:性别字段的数据转换器
* @Author wang_qz
* @Date 2021/8/15 19:16
* @Version 1.0
*/
public class GenderConverter implements Converter<Integer> {
private static final String MALE = "男";
private static final String FEMALE = "女";
private static final String NONE = "未知";
// Java数据类型 integer
@Override
public Class supportJavaTypeKey() {
return Integer.class;
}
// Excel文件中单元格的数据类型 string
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
// 读取Excel文件时将string转换为integer
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration)
throws Exception {
String value = cellData.getStringValue();
if (Objects.equals(FEMALE, value)) {
return 0; // 0-女
} else if (Objects.equals(MALE, value)) {
return 1; // 1-男
}
return 2; // 2-未知
}
// 写入Excel文件时将integer转换为string
@Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if (value == 1) {
return new CellData(MALE);
} else if (value == 0) {
return new CellData(FEMALE);
}
return new CellData(NONE); // 不男不女
}
}
EasyExcel导出
前端
// 下载
export function download() {
return request({
url: '/sysUser/DownLoadExcel',
responseType: 'blob',
method: 'get',
})
}
<template>
<div>
<!--方法一-->
<el-button size="small" type="primary" @click="download">点击下载</el-button>
<!--方法二-->
<a href="/sysUser/DownLoadExcel">下载</a>
</div>
</template>
<script>
import {download} from "@/api/user/user";
export default {
name: "index",
methods: {
// 下载
download() {
download().then(res => {
console.log(res)
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
let url = window.URL.createObjectURL(blob);
const link = document.createElement('a'); //创建a标签
link.href = url;
link.download = '通用信息.xlsx'; //重命名文件
link.click();
URL.revokeObjectURL(url);
})
},
}
}
</script>
后端
<!-- EasyExcel核心文件 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
</dependency>
package com.example.admin.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@ToString
@NoArgsConstructor
public class User {
@ExcelProperty("用户编号")
private Integer userId;
@ExcelProperty("用户名称")
private String userName;
@ExcelProperty("用户性别")
private String gender;
@ExcelProperty("创建时间")
private Date createTime;
public User(Integer userId, String userName, String gender, Date createTime) {
this.userId = userId;
this.userName = userName;
this.gender = gender;
this.createTime = createTime;
}
}
package com.example.admin.controller;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.User;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* (SysUser)表控制层
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
@GetMapping("DownLoadExcel")
public void doDownLoadExcel(HttpServletResponse response) throws IOException {
/**
* EasyExcel下载步骤
*/
//设置响应头
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//设置防止文件名中文乱码
String fileName = URLEncoder.encode("user1中文文件名", "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//构建写入到Excel中的数据(此数据可以从数据库中获取)
List<User> users = new ArrayList<>();
User user1 = new User(1001, "李四1", "男", new Date());
User user2 = new User(1002, "李四2", "男", new Date());
User user3 = new User(1003, "李四3", "男", new Date());
users.add(user1);
users.add(user2);
users.add(user3);
EasyExcel.write(response.getOutputStream(), User.class).sheet("用户信息").doWrite(users);
//Set<String> excludeColumnFiledNames = new HashSet<>();
//excludeColumnFiledNames.add("arrears");//某个你不要的属性名
//这里需要注意的是该属性需在最后一位,否则会把该属性及其后面属性都截取掉
//EasyExcel.write(response.getOutputStream(), ImportExcelParam.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("模板").doWrite(data(param));
}
}
EasyExcel导入
前端
<template>
<div>
<el-upload
style="width: 400px"
:data="userForm"
action="/sysUser/uploadExcel"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传Excel文件,且不超过500kb</div>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
// 文件数量
fileList: []
}
},
methods: {
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
console.log(file, fileList);
},
// 点击文件列表中已上传的文件时的钩子
handlePreview(file) {
console.log(file);
},
// 限制上传文件的个数和定义超出限制时的行为
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
// 文件列表移除文件时之前的钩子
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
}
}
}
</script>
<style>
.el-dropdown-links {
display: flex;
text-align: center;
line-height: 50px;
}
.el-dropdown-links img {
width: 100px;
height: 100px;
border-radius: 50px;
}
</style>
后端
package com.example.admin.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.User;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* (SysUser)表控制层
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@PostMapping("uploadExcel")
public void doposts(MultipartFile file) throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//设置单个文件为3M
fileUpload.setFileSizeMax(1024 * 1024 * 3);
//总文件大小为30M
fileUpload.setSizeMax(1024 * 1024 * 3 * 10);
// 获取上传的文件流
InputStream inputStream = file.getInputStream();
// 读取Excel
EasyExcel.read(inputStream, User.class,new AnalysisEventListener<User>() {
// 每解析一行数据,该方法会被调用一次
@Override
public void invoke(User data, AnalysisContext analysisContext) {
System.out.println("解析数据为:" + data.toString());
}
// 全部解析完成被调用
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("解析完成...");
// 可以将解析的数据保存到数据库
}
}).sheet().doRead();
}
}
优化
package com.example.admin.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
public class EasyExcelUtils {
/**
* 获取读取Excel的监听器对象
* 为了解耦及减少每个数据模型bean都要创建一个监听器的臃肿, 使用泛型指定数据模型类型
* 使用jdk8新特性中的函数式接口 Consumer
* 可以实现任何数据模型bean的数据解析, 不用重复定义监听器
* @param consumer 处理解析数据的函数, 一般可以是数据入库逻辑的函数
* @param threshold 阈值,达到阈值就处理一次存储的数据
* @param <T> 数据模型泛型
* @return 返回监听器
*/
public static <T> AnalysisEventListener<T> getReadListener(Consumer<List<T>> consumer, int threshold) {
return new AnalysisEventListener<T>() {
/**
* 存储解析的数据 T t
*/
// ArrayList基于数组实现, 查询更快
// List<T> dataList = new ArrayList<>(threshold);
// LinkedList基于双向链表实现, 插入和删除更快
List<T> dataList = new LinkedList<>();
/**
* 每解析一行数据事件调度中心都会通知到这个方法, 订阅者1
* @param data 解析的每行数据
* @param context
*/
@Override
public void invoke(T data, AnalysisContext context) {
dataList.add(data);
// 达到阈值就处理一次存储的数据
if (dataList.size() >= threshold) {
consumer.accept(dataList);
dataList.clear();
}
}
/**
* excel文件解析完成后,事件调度中心会通知到该方法, 订阅者2
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 最后阈值外的数据做处理
if (dataList.size() > 0) {
consumer.accept(dataList);
}
}
};
}
/**
* 获取读取Excel的监听器对象, 不指定阈值, 默认阈值为 2000
* @param consumer
* @param <T>
* @return
*/
public static <T> AnalysisEventListener<T> getReadListener(Consumer<List<T>>consumer) {
return getReadListener(consumer, 2000);
}
}
package com.example.admin.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.User;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.EasyExcelUtils;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* (SysUser)表控制层
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@PostMapping("uploadExcel")
public void doposts(MultipartFile file) throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//设置单个文件为3M
fileUpload.setFileSizeMax(1024 * 1024 * 3);
//总文件大小为30M
fileUpload.setSizeMax(1024 * 1024 * 3 * 10);
// 获取上传的文件流
InputStream inputStream = file.getInputStream();
// 读取excel
EasyExcel.read(inputStream, User.class, EasyExcelUtils.getReadListener(dataProcess())).doReadAll(); // 读取全部sheet
}
/**
* 传给监听器的是一个处理解析数据的函数, 当调用consumer的accept方法时就会调用传递的函数逻辑
* 这里传递的函数是对解析结果集的遍历打印操作, 也可以是数据入库操作
* @return
*/
public Consumer<List<User>> dataProcess() {
// Consumer<List<User>> consumer = users -> users.forEach(System.out::println);
Consumer<List<User>> consumer = users -> {
System.out.println(users);
};
return consumer;
}
}
案例
<template>
<div>
<div style="display: flex;justify-content: space-between">
<div>
<el-row style="margin-top: 10px">
<el-button
@click="downloadClicks"
type="primary"
icon="el-icon-download">下载
</el-button>
<el-upload
style="width: 400px"
action="/sysUser/uploadExcel"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-success="onSuccess"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传Excel文件,且不超过500kb</div>
</el-upload>
</el-row>
</div>
</div>
<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
style="width: 100%;margin-top: 10px;">
<el-table-column type="selection" header-align="center" align="center" width="50">
</el-table-column>
<el-table-column prop="uid" header-align="center" align="center" label="用户id"></el-table-column>
<el-table-column prop="userName" header-align="center" align="center" label="用户名"></el-table-column>
<el-table-column prop="avatar" header-align="center" align="center" label="头像地址">
<template slot-scope="scope">
<img :src="scope.row.avatar" style="width: 100px; height: 80px">
</template>
</el-table-column>
<el-table-column prop="nickName" header-align="center" align="center" label="昵称"></el-table-column>
<el-table-column prop="phoneNumber" header-align="center" align="center" label="电话号码"></el-table-column>
<el-table-column prop="sex" header-align="center" align="center" label="性别">
<template slot-scope="scope">
<span v-if="scope.row.sex == true">男</span>
<span v-else-if="scope.row.sex ==false">女</span>
</template>
</el-table-column>
<el-table-column prop="email" header-align="center" align="center" label="邮箱"></el-table-column>
<el-table-column prop="userDate" header-align="center" align="center" label="创建时间"></el-table-column>
<el-table-column
fixed="right"
header-align="center"
align="center"
width="150"
label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="addEditClick('edit',scope.row)" type="success">编辑</el-button>
<el-button size="mini" @click="deleteClick(scope.row)" type="danger">删除</el-button>
</template>
</el-table-column>
</el-table>
<div style="display: flex;justify-content: flex-end">
<el-pagination
background
@current-change="currentChange"
@size-change="sizeChange"
:page-sizes="[5, 10, 20, 30]"
:page-size="5"
layout="sizes, prev, pager, next, jumper, ->, total"
:total="total">
</el-pagination>
</div>
</div>
</template>
<script>
import {deleteUser, deleteUserIds, download, getUser} from "@/api/user/user";
export default {
name: "list",
data() {
return {
dialogVisible: false, //是否弹出,弹出层
dataList: [{//数据
uid: 0,
userName: "",
nickName: "",
sex: 1,
avatar: "",
phoneNumber: "",
email: "",
userState: 1,
userDate: ""
}],
dataListLoading: false,//进度条
dataListSelections: [],//多选框
currentPage: 1,//第一页
size: 6,//显示数量
total: 0,//有几条数据
userName: '',//搜索框// 文件数量
fileList: []
}
},
//钩子函数,刷新表格数据
created() {
this.initUser();
},
methods: {
downloadClicks() {
download(this.dataListSelections).then(res => {
console.log(res)
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
let url = window.URL.createObjectURL(blob);
const link = document.createElement('a'); //创建a标签
link.href = url;
link.download = '通用订单信息.xlsx'; //重命名文件
link.click();
URL.revokeObjectURL(url);
this.initUser();
})
},
// 文件上传成功时的钩子
onSuccess(res, file){
this.initUser();
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
console.log(file, fileList);
},
// 点击文件列表中已上传的文件时的钩子
handlePreview(file) {
console.log(file);
},
// 限制上传文件的个数和定义超出限制时的行为
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
// 文件列表移除文件时之前的钩子
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`);
},
//父组件接收子组件传的方法
initUsers() {
this.initUser();
},
//表格数据加搜索
initUser() {
this.dataListLoading = true;
getUser(Object.assign({
current: this.currentPage,
size: this.size,
userName: this.userName
})).then(resp => {
this.dataListLoading = false;
if (resp) {
this.dataList = resp.data.records;//表格数据
this.total = resp.data.total;//总页数
}
})
},
// 多选
selectionChangeHandle(val) {
var subStr = "";
val.forEach((res) => {
subStr += res.uid + ","
})
var ids = subStr.substring(0, subStr.length - 1).split(",")
console.log(ids)
this.dataListSelections = ids;
},
//显示页数
sizeChange(size) {
this.size = size;
this.initUser();
},
//页数比如:第几页
currentChange(currentPage) {
this.currentPage = currentPage;
this.initUser();
},
}
}
</script>
<style scoped>
</style>
package com.example.admin.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
public class EasyExcelUtils {
/**
* 获取读取Excel的监听器对象
* 为了解耦及减少每个数据模型bean都要创建一个监听器的臃肿, 使用泛型指定数据模型类型
* 使用jdk8新特性中的函数式接口 Consumer
* 可以实现任何数据模型bean的数据解析, 不用重复定义监听器
* @param consumer 处理解析数据的函数, 一般可以是数据入库逻辑的函数
* @param threshold 阈值,达到阈值就处理一次存储的数据
* @param <T> 数据模型泛型
* @return 返回监听器
*/
public static <T> AnalysisEventListener<T> getReadListener(Consumer<List<T>> consumer, int threshold) {
return new AnalysisEventListener<T>() {
/**
* 存储解析的数据 T t
*/
// ArrayList基于数组实现, 查询更快
// List<T> dataList = new ArrayList<>(threshold);
// LinkedList基于双向链表实现, 插入和删除更快
List<T> dataList = new LinkedList<>();
/**
* 每解析一行数据事件调度中心都会通知到这个方法, 订阅者1
* @param data 解析的每行数据
* @param context
*/
@Override
public void invoke(T data, AnalysisContext context) {
dataList.add(data);
// 达到阈值就处理一次存储的数据
if (dataList.size() >= threshold) {
consumer.accept(dataList);
dataList.clear();
}
}
/**
* excel文件解析完成后,事件调度中心会通知到该方法, 订阅者2
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 最后阈值外的数据做处理
if (dataList.size() > 0) {
consumer.accept(dataList);
}
}
};
}
/**
* 获取读取Excel的监听器对象, 不指定阈值, 默认阈值为 2000
* @param consumer
* @param <T>
* @return
*/
public static <T> AnalysisEventListener<T> getReadListener(Consumer<List<T>>consumer) {
return getReadListener(consumer, 2000);
}
}
package com.example.admin.entity;
import java.util.Date;
import java.io.Serializable;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* (SysUser)实体类
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Data
@ToString
@NoArgsConstructor
public class SysUser implements Serializable {
private static final long serialVersionUID = 618482421024552973L;
/**
* 用户id
*/
@ExcelIgnore
@TableId(type = IdType.AUTO)
private Integer uid;
/**
* 账号
*/
@ExcelProperty("账号")
private String userName;
/**
* 用户名
*/
@ExcelProperty("用户名")
private String nickName;
/**
* 密码
*/
@ExcelIgnore
private String password;
/**
* 用户性别(0男 1女 2未知)
*/
@ExcelProperty("用户性别(0男 1女 2未知)")
private String sex;
/**
* 头像
*/
@ExcelProperty("头像")
private String avatar;
/**
* 手机号码
*/
@ExcelProperty("手机号码")
private String phoneNumber;
/**
* 邮箱
*/
@ExcelProperty("邮箱")
private String email;
/**
* 帐号状态(0正常 1停用)
*/
@ExcelProperty("帐号状态(0正常 1停用)")
private Integer userState;
/**
* 注册时间
*/
@ExcelProperty("注册时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")// 后台传数据到前台
private Date userDate;
}
package com.example.admin.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.SysUser;
import com.example.admin.entity.User;
import com.example.admin.service.SysUserService;
import com.example.admin.utils.EasyExcelUtils;
import com.example.admin.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* (SysUser)表控制层
*
* @author makejava
* @since 2022-05-23 17:33:13
*/
@Slf4j
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@PostMapping("DownLoadExcel")
public void dopost(@RequestBody List<Long> idList, HttpServletResponse response) throws IOException {
/**
* EasyExcel下载步骤
*/
//设置响应头
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//设置防止文件名中文乱码
String fileName = URLEncoder.encode("user1中文文件名", "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//构建写入到Excel中的数据(此数据可以从数据库中获取)
List<SysUser> sysUsers = sysUserService.listByIds(idList);
EasyExcel.write(response.getOutputStream(), SysUser.class).sheet("用户信息").doWrite(sysUsers);
}
@PostMapping("uploadExcel")
public void doposts(MultipartFile file) throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//设置单个文件为3M
fileUpload.setFileSizeMax(1024 * 1024 * 3);
//总文件大小为30M
fileUpload.setSizeMax(1024 * 1024 * 3 * 10);
// 获取上传的文件流
InputStream inputStream = file.getInputStream();
// 读取excel
EasyExcel.read(inputStream, SysUser.class, EasyExcelUtils.getReadListener(dataProcess())).doReadAll(); // 读取全部sheet
}
/**
* 传给监听器的是一个处理解析数据的函数, 当调用consumer的accept方法时就会调用传递的函数逻辑
* 这里传递的函数是对解析结果集的遍历打印操作, 也可以是数据入库操作
* @return
*/
public Consumer<List<SysUser>> dataProcess() {
Consumer<List<SysUser>> consumer = users -> {
sysUserService.saveBatch(users);
};
return consumer;
}
}