




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
第SpringBoot整合EasyExcel實現(xiàn)導入導出數(shù)據(jù)目錄前言1.前端2.數(shù)據(jù)庫3.后端3.1contrller3.2mapper3.3bean3.4listener3.5config3.6配置文件4.啟動測試
前言
創(chuàng)建一個普通的maven項目即可
項目目錄結(jié)構(gòu)
1.前端
存放在resources/static下
index.html
!DOCTYPEhtml
htmllang="en"
head
metacharset="UTF-8"/
metahttp-equiv="X-UA-Compatible"content="IE=edge"/
metaname="viewport"content="width=device-width,initial-scale=1.0"/
titleDocument/title
!--開發(fā)環(huán)境版本,包含了有幫助的命令行警告--
scriptsrc="/npm/vue@2/dist/vue.js"/script
!--引入樣式--
link
rel="stylesheet"
href="/element-ui/lib/theme-chalk/index.css"rel="externalnofollow"
!--引入組件庫--
scriptsrc="/element-ui/lib/index.js"/script
scriptsrc="/axios/dist/axios.min.js"/script
/head
body
divid="app"
div
div
el-button
@click="dialogVisible=true"
type="primary"
size="mini"
icon="el-icon-download"
導入Excel
/el-button
el-dialog
title="數(shù)據(jù)字典導入"
:visible.sync="dialogVisible"
width="30%"
el-form
el-form-itemlabel="請選擇Excel文件"
el-upload
:auto-upload="true"
:multiple="false"
:limit="1"
:on-exceed="fileUploadExceed"
:on-success="fileUploadSuccess"
:on-error="fileUploadError"
:action="importUrl"
name="file"
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
!--accept只接受某種格式的文件--
el-buttonsize="small"type="primary"點擊上傳/el-button
/el-upload
/el-form-item
/el-form
divslot="footer"
el-button@click="dialogVisible=false"取消/el-button
/div
/el-dialog
!--導出--
el-button
@click="exportData"
type="primary"
size="mini"
icon="el-icon-upload2"
導出Excel
/el-button
!--數(shù)據(jù)展示--
el-table:data="list"stripe
el-table-columnprop="name"label="姓名"width="180"
/el-table-column
el-table-columnprop="birthday"label="生日"width="180"
/el-table-column
el-table-columnprop="salary"label="薪資"/el-table-column
/el-table
div
el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current="pageNum"
:sizes="[2,5,10,20]"
:size="pageSize"
background
layout="total,sizes,prev,pager,next,jumper"
:total="total"
/el-pagination
/div
/div
/div
/div
/body
script
newVue({
el:'#app',
data(){
return{
dialogVisible:false,//文件上傳對話框是否顯示
list:[],//字典的數(shù)據(jù)
importUrl:'http://localhost:8811/api/excel/import',
pageNum:1,//頁數(shù)
pageSize:5,//每頁條數(shù)
total:1000,
created(){
this.showList()
methods:{
showList(){
//使用自定義配置
constrequest=axios.create({
baseURL:'http://localhost:8811',//url前綴
timeout:1000,//超時時間
//headers:{token:'helen123456'},//攜帶令牌
request
.get('/api/excel/list',{
params:{
pageNum:this.pageNum,
pageSize:this.pageSize,
.then((res)={
this.total=res.data.size
this.list=res.data.list
console.log(res)
//上傳多于一個文件時
fileUploadExceed(){
this.$message.warning('只能選取一個文件')
//導出
exportData(){
window.location.href='http://localhost:8811/api/excel/export'
//上傳成功回調(diào)
fileUploadSuccess(response){
if(response.code===0){
this.$message.success('數(shù)據(jù)導入成功')
this.dialogVisible=false
}else{
this.$message.error(response.message)
//上傳失敗回調(diào)
fileUploadError(error){
this.$message.error('數(shù)據(jù)導入失敗')
*用戶所選擇當前頁面展示的數(shù)據(jù)條數(shù)
handleSizeChange(val){
console.log(`每頁${val}條`)
this.pageSize=val
this.showList()
handleCurrentChange(val){
console.log(`當前頁:${val}`)
this.pageNum=val
this.showList()
/script
/html
2.數(shù)據(jù)庫
CREATETABLE`student`(
`name`varchar(255)DEFAULTNULLCOMMENT'姓名',
`birthday`datetimeDEFAULTNULLCOMMENT'生日',
`salary`decimal(10,4)DEFAULTNULLCOMMENT'薪資'
)ENGINE=InnoDBDEFAULTCHARSET=utf8mb4;
3.后端
3.1contrller
StudentController
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/excel/")
publicclassStudentController{
@Resource
privateStudentMapperstudentMapper;
@GetMapping("list")
publicHashMapString,Objectlist(@RequestParamintpageNum,@RequestParamintpageSize){
//分頁查詢
PageStudentpage=newPage(pageNum,pageSize);
studentMapper.selectPage(page,null);
//封裝數(shù)據(jù)
HashMapString,Objectmap=newHashMap();
ArrayListExcelStudentDTOexcelDictDTOList=newArrayList();
//轉(zhuǎn)換數(shù)據(jù)
page.getRecords().forEach(student-{
ExcelStudentDTOstudentDTO=newExcelStudentDTO();
BeanUtils.copyProperties(student,studentDTO);
excelDictDTOList.add(studentDTO);
map.put("list",excelDictDTOList);
map.put("size",page.getTotal());
returnmap;
*導入
*@paramfile文件對象
@RequestMapping("import")
@Transactional(rollbackFor={Exception.class})
publicStringimportData(@RequestParam("file")MultipartFilefile){
try{
//讀取文件流
EasyExcel.read
(file.getInputStream(),//前端上傳的文件
ExcelStudentDTO.class,//跟excel對應的實體類
newExcelDictDTOListener(studentMapper))//監(jiān)聽器
.excelType(ExcelTypeEnum.XLSX)//excel的類型
.sheet("模板").doRead();
("importDatafinished");
}catch(IOExceptione){
("失敗");
e.printStackTrace();
return"上傳成功";
*導入
@GetMapping("export")
publicStringexportData(HttpServletResponseresponse){
try{
//設置響應體內(nèi)容
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
//這里URLEncoder.encode可以防止中文亂碼當然和easyexcel沒有關(guān)系
StringfileName=URLEncoder.encode("myStu","UTF-8").replaceAll("\\+","%20");
response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
EasyExcel.write(response.getOutputStream()
,ExcelStudentDTO.class).sheet().doWrite(studentMapper.selectList(null));
}catch(Exceptione){
e.printStackTrace();
return"上傳成功";
}
3.2mapper
StudentMapper
@Mapper
publicinterfaceStudentMapperextendsBaseMapperStudent{
voidinsertBatch(ListExcelStudentDTOlist);
}
StudentMapper.xml
xmlversion="1.0"encoding="UTF-8"
!DOCTYPEmapperPUBLIC"-////DTDMapper3.0//EN""/dtd/mybatis-3-mapper.dtd"
mappernamespace="look.word.mapper.StudentMapper"
insertid="insertBatch"
insertintostudent(name,birthday,salary)
values
foreachcollection="list"item="item"separator=","
#{},
#{item.birthday},
#{item.salary}
/foreach
/insert
/mapper
3.3bean
ExcelStudentDTO
導入數(shù)據(jù)時要保證excel中列名和ExcelStudentDTO一致奧
/**
*excel對應的實體類
*@authorjiejie
@Data
publicclassExcelStudentDTO{
//excel中的列名
@ExcelProperty("姓名")
privateStringname;
@ExcelProperty("生日")
privateDatebirthday;
@ExcelProperty("薪資")
privateBigDecimalsalary;
}
Student
/**
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 創(chuàng)“魯班獎”方案
- 變壓器結(jié)構(gòu)簡介
- 寢室衛(wèi)生安全管理制度
- 小區(qū)規(guī)則宿舍管理制度
- 凍干粉針劑97課件
- 國網(wǎng)公司食堂管理制度
- 醫(yī)療資源協(xié)助管理制度
- 工地門衛(wèi)煙酒管理制度
- 培訓機構(gòu)餐廳管理制度
- 原料庫房退料管理制度
- 第五章 SPSS基本統(tǒng)計分析課件
- 2025年計算機Photoshop操作實務的試題及答案
- 2025時事熱點政治題及參考答案(滿分必刷)
- GB/T 23453-2025天然石灰石建筑板材
- 2024-2030全球WiFi 6移動熱點行業(yè)調(diào)研及趨勢分析報告
- 砌磚理論考試題及答案
- 中醫(yī)針灸治療腦梗塞后遺癥的應用實踐
- 2025年高等數(shù)學期末考試試題及答案
- 2024中國國新基金管理有限公司相關(guān)崗位招聘7人筆試參考題庫附帶答案詳解
- 2025屆各地名校4月上旬高三語文聯(lián)考作文題目及范文12篇匯編
- 【9語一?!?025年4月天津市和平區(qū)九年級中考一模語文試卷(含答案)
評論
0/150
提交評論