Java使用EasyExcel實現(xiàn)Excel的導(dǎo)入導(dǎo)出
前言
在真實的開發(fā)者場景中,經(jīng)常會使用excel作為數(shù)據(jù)的載體,進行數(shù)據(jù)導(dǎo)入和導(dǎo)出的操作,使用excel的導(dǎo)入和導(dǎo)出有很多種解決方案,本篇記錄一下EasyExcel的使用。
一、EasyExcel是什么?
EasyExcel是一個開源的項目,是阿里開發(fā)的。EasyExcel可以簡化Excel表格的導(dǎo)入和導(dǎo)出操作,使用起來簡單快捷,易上手。
二、使用步驟
1.導(dǎo)入依賴
在pom.xml中導(dǎo)入我們需要使用的依賴
<!--文件上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- easy excel依賴 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>2.編寫文件上傳配置
在springMVC配置文件中添加如下配置
<!-- 文件上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)為ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上傳文件大小上限,單位為字節(jié)(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
</bean>3.配置表頭對應(yīng)實體類
package com.lzl.entityBo;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
/**
* --效率,是成功的核心關(guān)鍵--
*
* @Author lzl
* @Date 2022/10/29 13:59
*/
public class EmployeeBo {
@ExcelProperty(value = "工號")//表頭注解
private Integer emp_no;
@ExcelProperty(value = "姓名")
private String emp_name;
@ExcelProperty(value = "性別")
private String emp_gender;
@ExcelProperty(value = "年齡")
private Integer emp_age;
@ExcelIgnore//不輸出該列
private Integer emp_dept_no;
@ExcelProperty(value = "薪資")
private Double emp_salary;
@ExcelProperty(value = "入職時間")
@DateTimeFormat("yyyy-MM-dd")//格式化日期時間
private String emp_hire_time;
@ExcelProperty(value = "職位")
private String emp_position;
@ExcelProperty(value = "狀態(tài)")
private Integer emp_status;
public EmployeeBo() {
}
public EmployeeBo(Integer emp_no, String emp_name, String emp_gender, Integer emp_age, Integer emp_dept_no, Double emp_salary, String emp_hire_time, String emp_position, Integer emp_status) {
this.emp_no = emp_no;
this.emp_name = emp_name;
this.emp_gender = emp_gender;
this.emp_age = emp_age;
this.emp_dept_no = emp_dept_no;
this.emp_salary = emp_salary;
this.emp_hire_time = emp_hire_time;
this.emp_position = emp_position;
this.emp_status = emp_status;
}
public Integer getEmp_no() {
return emp_no;
}
public void setEmp_no(Integer emp_no) {
this.emp_no = emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getEmp_gender() {
return emp_gender;
}
public void setEmp_gender(String emp_gender) {
this.emp_gender = emp_gender;
}
public Integer getEmp_age() {
return emp_age;
}
public void setEmp_age(Integer emp_age) {
this.emp_age = emp_age;
}
public Integer getEmp_dept_no() {
return emp_dept_no;
}
public void setEmp_dept_no(Integer emp_dept_no) {
this.emp_dept_no = emp_dept_no;
}
public Double getEmp_salary() {
return emp_salary;
}
public void setEmp_salary(Double emp_salary) {
this.emp_salary = emp_salary;
}
public String getEmp_hire_time() {
return emp_hire_time;
}
public void setEmp_hire_time(String emp_hire_time) {
this.emp_hire_time = emp_hire_time;
}
public String getEmp_position() {
return emp_position;
}
public void setEmp_position(String emp_position) {
this.emp_position = emp_position;
}
public Integer getEmp_status() {
return emp_status;
}
public void setEmp_status(Integer emp_status) {
this.emp_status = emp_status;
}
@Override
public String toString() {
return "EmployeeBo{" +
"emp_no=" + emp_no +
", emp_name='" + emp_name + '\'' +
", emp_gender='" + emp_gender + '\'' +
", emp_age=" + emp_age +
", emp_dept_no=" + emp_dept_no +
", emp_salary=" + emp_salary +
", emp_hire_time='" + emp_hire_time + '\'' +
", emp_position='" + emp_position + '\'' +
", emp_status=" + emp_status +
'}';
}
}
4.監(jiān)聽器編寫
使用EasyExcel需要進行全局監(jiān)聽配置新建一個listener包,并在該包下新建一個MyListener類,繼承AnalysisEventListener類,泛型設(shè)置為當(dāng)前需要導(dǎo)出的類,我這里需要導(dǎo)出的是員工數(shù)據(jù),因此我將泛型設(shè)置為員工類,整體代碼如下:
package com.lzl.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.lzl.entity.Employee;
import com.lzl.entityBo.EmployeeBo;
import com.lzl.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//easy excel 監(jiān)聽器
@Component
@Scope("prototype")//標(biāo)記此處的監(jiān)聽器為多例的,防止并發(fā)讀操作時出現(xiàn)錯誤
public class EmployeeReadListener extends AnalysisEventListener<EmployeeBo> {
//此處自動注入業(yè)務(wù)層的新增功能
@Autowired
private EmployeeService service;
@Override
public void invoke(EmployeeBo data, AnalysisContext analysisContext) {
//每讀取一行數(shù)據(jù)都會調(diào)用一次,會把每一行數(shù)據(jù)封裝到employee
//屬性不一致時,使用屬性拷貝
Employee employee = new Employee();
BeanUtils.copyProperties(data,employee);
service.addNewEmployee(employee);//調(diào)用新增方法
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//所有數(shù)據(jù)解析完畢執(zhí)行該方法
}
}此處監(jiān)聽器的作用是,當(dāng)我們每次從excel表格中讀取一行數(shù)據(jù)時,我們都需要進行新增操作,而新增操作交給我們的監(jiān)聽器去完成。
5.控制層
控制層負(fù)責(zé)接收前端傳過來的文件流,然后使用EasyExcel來對導(dǎo)入或者導(dǎo)出的數(shù)據(jù)進行進一步的處理,并把處理結(jié)果返回,需要注意的是,對于導(dǎo)出操作,該方法并沒有返回值,因此我們不需要返回值,而對于導(dǎo)入方法,此處我使用的是layui的前端,所以返回的數(shù)據(jù)格式是layui可以接收的工具類。
package com.lzl.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.lzl.entityBo.EmployeeBo;
import com.lzl.listener.EmployeeReadListener;
import com.lzl.service.EmployeeService;
import com.lzl.util.ResultLayUi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
@Controller
@RequestMapping("/excel")
public class UploadExcelController {
//注入監(jiān)聽器
@Autowired
private EmployeeReadListener listener;
//注入業(yè)務(wù)層
@Autowired
private EmployeeService service;
/**
*
* @param file 獲得前端上傳的文件 EasyExcel.read 需要傳入三個參數(shù) 文件流 操作實體類的字節(jié)碼 監(jiān)聽器
* @return 0 成功上傳
* @throws IOException
*/
@RequestMapping("read")
@ResponseBody
public ResultLayUi<String> readExcel(MultipartFile file) throws IOException {
// 得到excel讀取對象 //通過文件獲得流, 獲得讀取文件的class 填入監(jiān)聽器 監(jiān)聽器每讀取一行就執(zhí)行一次新增
ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), EmployeeBo.class, listener);
//獲取表格
ExcelReaderSheetBuilder sheet = read.sheet();
//讀取表格
sheet.doRead();
ResultLayUi<String> resultLayUi = new ResultLayUi<String>();
resultLayUi.setCode(0);
resultLayUi.setMsg("已成功導(dǎo)入");
return resultLayUi;
}
@RequestMapping("write")
public void writeExcel(String nos,HttpServletResponse response) throws IOException {
//設(shè)置響應(yīng)頭
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//導(dǎo)出的文件名
String filename = URLEncoder.encode("員工信息","utf-8");
//設(shè)置響應(yīng)頭
response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
//獲得流對象
ServletOutputStream outputStream = response.getOutputStream();
//獲得write對象
ExcelWriterBuilder write = EasyExcel.write(outputStream, EmployeeBo.class);
//獲得數(shù)據(jù)表對象
ExcelWriterSheetBuilder sheet = write.sheet();
//準(zhǔn)備需要輸出的數(shù)據(jù) 調(diào)用業(yè)務(wù)層,獲得所有需要導(dǎo)出的數(shù)據(jù)
List<EmployeeBo> list = service.getExcelDataByNos(nos);
//生成表格文件
sheet.doWrite(list);
}
}6.前端代碼
前端使用的是layui的文件上傳組件。所有相關(guān)代碼如下:
下載:這里我使用了switch-case分支來對多個按鈕的事件進行區(qū)分和綁定,layui的組件加載:
layui.use(['table', 'layer', 'form', 'laydate', 'transfer','upload','element'], function () {
var table = layui.table;
var layer = layui.layer;
var form = layui.form;
var laydate = layui.laydate;
var transfer = layui.transfer;
var upload = layui.upload;
var element = layui.element;
var $ = layui.$;按鈕:
<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="write">
<i class="layui-icon"></i>導(dǎo)出數(shù)據(jù)
</button>
<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="read">
<i class="layui-icon"></i>導(dǎo)入數(shù)據(jù)
</button>上傳彈出層:
<!-- 上傳excel表格 區(qū)域-->
<div class="layui-form-item" id="import" style="display:none;">
<form class="layui-form" onsubmit="return false;" id="readExcel">
<div class="layui-form-item">
<label class="layui-form-label"></label>
<div class="layui-input-block">
<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上傳文件</button>
<div style="width: 95px;">
<div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
<div class="layui-progress-bar" lay-percent=""></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div> case 'write':
if (data.length === 0) {
layer.msg('請至少選擇一行');
} else if (data.length > 1) {
$list = checkStatus.data;
$ids = [];
for (var i = 0; i < $list.length; i++) {
$ids[i] = $list[i].emp_no;
}
$strIds = ""
for (var i = 0; i < $ids.length; i++) {
$strIds += $ids[i] + ",";
}
layer.confirm("確認(rèn)導(dǎo)出所有選中行嗎?", function (index) {
window.location.href = "http://localhost:8080/excel/write?nos=" + $strIds;
layer.close(index);
});
}
break;
case 'read':
layer.open({
type: 1,
title: '上傳excel文件',
area: ['300px', '300px'],
content: $('#import')
//這里content是一個DOM,注意:最好該元素要存放在body最外層,否則可能被其它的相對元素所影響
});
break;
//上傳文件的事件:
//常規(guī)使用 - excel表格上傳
upload.render({
elem: '#test1'
,accept: 'file' //普通文件
,exts: 'xlsx' //上傳文件格式
, url: 'http://localhost:8080/excel/read'
, done: function (res) {
console.log(res);
//如果上傳失敗
if (res.code > 0) {
layer.msg('上傳失敗');
} else {
active.reload();
layer.msg(res.msg, {
icon: 6,
time: 1500 //2秒關(guān)閉(如果不配置,默認(rèn)是3秒)
}, function () {
//關(guān)閉彈出層
layer.closeAll();
element.progress('demo', '0%'); //進度條復(fù)位
});
}
}
//進度條
, progress: function (n, elem, e) {
element.progress('demo', n + '%'); //可配合 layui 進度條元素使用
if (n == 100) {
//layer.msg('上傳完畢', { icon: 1 });
}
}
});總結(jié)
EasyExcel是一個excel導(dǎo)入導(dǎo)出的解決方案,非常好用。
到此這篇關(guān)于Java使用EasyExcel實現(xiàn)Excel的導(dǎo)入導(dǎo)出的文章就介紹到這了,更多相關(guān)EasyExcel實現(xiàn)Excel導(dǎo)入導(dǎo)出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot中EasyExcel實現(xiàn)Excel文件的導(dǎo)入導(dǎo)出
- SpringBoot集成EasyExcel實現(xiàn)Excel導(dǎo)入的方法
- SpringBoot整合EasyExcel實現(xiàn)文件導(dǎo)入導(dǎo)出
- java使用EasyExcel導(dǎo)入導(dǎo)出excel
- Java+EasyExcel實現(xiàn)文件的導(dǎo)入導(dǎo)出
- EasyExcel實現(xiàn)導(dǎo)入+各種數(shù)據(jù)校驗功能
- Java使用easyExcel批量導(dǎo)入數(shù)據(jù)詳解
- Java?EasyExcel導(dǎo)入帶圖片的完整過程記錄
相關(guān)文章
Java中的DelayQueue實現(xiàn)原理及應(yīng)用場景詳解
這篇文章主要介紹了Java中的DelayQueue實現(xiàn)原理及應(yīng)用場景詳解,DelayQueue是一個沒有邊界BlockingQueue實現(xiàn),加入其中的元素必需實現(xiàn)Delayed接口,當(dāng)生產(chǎn)者線程調(diào)用put之類的方法加入元素時,會觸發(fā)Delayed接口中的compareTo方法進行排序,需要的朋友可以參考下2023-12-12
Spring實現(xiàn)一個簡單的SpringIOC容器
本篇文章主要介紹了Spring實現(xiàn)一個簡單的SpringIOC容器,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04
Spring Boot2.0整合ES5實現(xiàn)文章內(nèi)容搜索實戰(zhàn)
這篇文章主要介紹了Spring Boot2.0整合ES5實現(xiàn)文章內(nèi)容搜索實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
SpringBoot+Redis使用AOP防止重復(fù)提交的實現(xiàn)
本文主要介紹了SpringBoot+Redis使用AOP防止重復(fù)提交的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Java Tree結(jié)構(gòu)數(shù)據(jù)中查找匹配節(jié)點方式
這篇文章主要介紹了Java Tree結(jié)構(gòu)數(shù)據(jù)中查找匹配節(jié)點方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
java 三種將list轉(zhuǎn)換為map的方法詳解
這篇文章主要介紹了java 三種將list轉(zhuǎn)換為map的方法詳解的相關(guān)資料,需要的朋友可以參考下2017-01-01
詳解在spring中使用JdbcTemplate操作數(shù)據(jù)庫的幾種方式
這篇文章主要介紹了詳解在spring中使用JdbcTemplate操作數(shù)據(jù)庫的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作
這篇文章主要介紹了MybatisPlus,無XML分分鐘實現(xiàn)CRUD操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

