npm install --save xlsx@0.17.0
npm install --save file-saver@2.0.5
Export2Excel.js 下载 :Export2Excel.js
<div >
<el-button type="success" plain icon="Download" @click="handleClick()">
导入
<input type="file" id="import" style="display: none;" @change="importExcel"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"/>
el-button>
<el-button type="warning" plain icon="Upload" @click="exportExcel()">导出el-button>
div>
<el-table :data="mockTableData" height="350" :header-cell-style="{background:'#F8F8F9',color:'#606266'}">
....
el-table>
<div class="level_table_bottom">
<el-config-provider :locale="locale">
<el-pagination :hide-on-single-page="false" background layout="sizes,total, prev, pager, next,jumper"
:current-page="currentPage" :total="totalPage" v-model:page-size="pageSize" :page-sizes="[5,10, 20, 50]"
@current-change="handleCurrentChange" @size-change="handleSizeChange">
el-pagination>
el-config-provider>
div>
import XLSX from "xlsx"
// 通过mock获取的总数据
import tableData from '@/mock/mockTable.js'
// element-plus设置为中文(默认英文)
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
const locale = ref(zhCn)
const totalData = ref([]) // 总数据
const mockTableData = ref([]) // 表格数据
const currentPage = ref(1) // 当前页
const totalPage = ref(0) // 总条数
const pageSize = ref(20) // 每页条数
onMounted(() =>{
totalData.value = tableData
getExcelPage()
console.log('getTableData',tableData);
})
const getExcelPage = async()=>{
let cutData = JSON.parse(JSON.stringify(totalData.value))
// 赋值给tableData
mockTableData.value = cutData.splice((currentPage.value - 1) * pageSize.value , pageSize.value)
totalPage.value = totalData.value.length
}
// 导入excel
/** 按钮点击使用 input type="file" 点击事件 */
const handleClick = ()=>{
return document.getElementById('import').click()
}
/** 导入excel的input的change 函数 */
const importExcel = (event) => {
console.log('file',event);
// FileReader 对象允许 Web 应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容
let fileReader = new FileReader()
var file = event.currentTarget.files[0]
console.log('file',file);
// 在读取操作完成时触发
fileReader.onload = (e)=>{
try{
// 读取本地excel文件
let data = e.target.result
let workbook = XLSX.read(data, { type: "binary"})
// 获取excel读取出的数据
let sheetName = workbook.SheetNames[0]
let excelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])
console.log('excelData',excelData);
// 处理数据
let arr = []
excelData.forEach(item =>{
let obj = {}
obj.id = item["ID"]
obj.name = item["名称"]
obj.videoId = item["视频ID"]
obj.videoTitle = item["视频标题"]
obj.release = item["发布"]
obj.videoType = item["视频类型"].split(/[,,]/)
obj.playVolume = item["播放量"]
obj.updateTime = item["上传时间"]
arr.push(obj)
})
// 重置页码
currentPage.value = 1
// 赋值给totalData
totalData.value = arr
// 前端分页
getExcelPage()
//置空input的值,防止重复上传同一文件失效
document.getElementById("import").value=''
}
catch(e){
ElMessage.error("请选择正确文件类型")
return false;
}
}
// 读取文件成功后执行上面的回调函数
fileReader.readAsBinaryString(file);
}
// 导出excel
/**导出按钮点击事件函数
* @前期准备 npm install -S xlsx file-saver 及 Export2Excel.js
*/
const exportExcel = ()=>{
import("@/utils/Export2Excel.js").then((excel) => {
// 导出的表头名
const tHeader = ["ID","名称", "视频ID","视频标题","发布","视频类型","播放量","上传时间"]
// 导出的表头字段名
const filterVal = [ "id","name","videoId","videoTitle","release","videoType","playVolume","updateTime"]
//传入的数据
const list = mockTableData.value
const data = formatJson(filterVal, list);
excel.export_json_to_excel({
header: tHeader, // 表格头部
data, // 表格数据
filename: "表格导出测试", // excel文件名
})
})
}
/**
* 格式化表格数据
* @filterVal 格式头
* @jsonData 用来格式化的表格数据
*/
const formatJson = (filterVal, jsonData) => {
return jsonData.map(v => filterVal.map(j => v[j]))
}