第一步:克隆或者下载下面的代码
git clone https://github.com/dream-num/Luckysheet.git
第二步:安装依赖
npm install
npm install gulp -g
第三步:运行
npm run dev
效果如下图所示
第四步:打包
打包执行成功后,在文件夹目录下会出现dis文件夹,如下图所示:
npm run build
第五步:本地引入
把dist文件夹中的代码全部复制粘贴到你项目的public文件夹中,index.html文件除外。
在你项目的index.html文件中引入如下代码,如果你复制的位置是其他地方,需要用绝对路径引入这些文件。
<link rel='stylesheet' href='./public/plugins/css/pluginsCss.css' />
<link rel='stylesheet' href='./public/plugins/plugins.css' />
<link rel='stylesheet' href='./public/css/luckysheet.css' />
<link rel='stylesheet' href='./public/assets/iconfont/iconfont.css' />
<script src="./public/plugins/js/plugin.js"></script>
<script src="./public/luckysheet.umd.js"></script>
接下来就是在项目中使用这个插件
首先要引入luckyexcel 的依赖,我们导入导出本地excel会用到
npm install luckyexcel --save
如果引入依赖报错可能是依赖冲突,可以使用下面的
npm install luckyexcel --save --force
然后创建一个vue页面文件
<template>
<div>
<div style="height: 10px;position: absolute">
<el-upload
ref="upload"
class="upload-demo"
action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
:limit="1"
:on-change="handleFileChange"
:auto-upload="false"
accept=".xlsx"
>
<template #trigger>
<el-button type="primary">select file</el-button>
</template>
</el-upload>
</div>
<div v-if="isShow" id="luckysheet" class="luckysheet-wrap"></div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import LuckyExcel from 'luckyexcel';
import {ElMessage} from "element-plus";
const isShow = ref(false)
function handleFileChange(file, newFileList) {
const selectedFile = file.raw;
if (!(selectedFile instanceof File)) {
console.error('传入了非文件对象');
return;
}
if (selectedFile.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
console.log('文件是xlsx类型');
} else {
console.error('不是xlsx文件');
ElMessage.error('请选择xlsx类型文件')
return;
}
let filename = selectedFile.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
let reader = new FileReader();
reader.onload = async (e) => {
let fileData = e.target.result;
try {
isShow.value = true
LuckyExcel.transformExcelToLucky(fileData, async (exportJson, luckysheetfile) => {
console.log(exportJson.sheets)
creatExcel(filename, JSON.stringify(exportJson.sheets))
});
} catch (e) {
console.error(e);
}
};
reader.onerror = function() {
console.error("File could not be read! Code " + reader.error.code);
};
reader.readAsArrayBuffer(selectedFile);
}
function creatExcel(title, content){
const options = {
container: 'luckysheet', // 设定DOM容器的id
title: 'excel 表格', // 设定表格名称
lang: 'zh', // 设定表格语言
hook: {
updated: (e) => {
//监听更新,并在1s后自动保存
$('#luckysheet_info_detail_save').text("已修改")
let title = $('#luckysheet_info_detail_input').val();
let content = luckysheet.getAllSheets();
//去除临时数据,减小体积
for (let i in content)
content[i].data = undefined
console.log(title)
console.log(content)
}
},
}
options.data = JSON.parse(content)
options.title = title;
window.luckysheet.create(options)
}
onMounted(() => {
});
</script>
<style scoped>
.luckysheet-wrap {
margin: 0px;
padding: 0px;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
}
</style>
点击按钮选择一个xlsx文件就能导入成功了,效果如下(这里只能导入xlsx文件,导入xls文件会报错,暂时不知道什么原因,如果有xls文件的话可以把表格另存为xlsx类型的文件再导入)
下面放一个完整的demo展示效果
<template>
<div style="width: 100%; height: 100vh;overflow: auto;">
<div>
<div style="display: flex;">
<div style="margin-right: 10px;">
<el-upload ref="upload" :auto-upload="false" accept=".xlsx" :show-file-list='false' :on-change="handleChangeUpload"
action="#" class="upload-demo" multiple>
<el-button type="primary">导入</el-button>
</el-upload>
</div>
<el-button type="primary" @click="goBack()">返回</el-button>
</div>
</div>
<span>电源配线图</span>
<el-table :data="dataList" width="100%" border :max-height="750">
<el-table-column label="序号" align="center" key="id" prop="id" fixed width="100px" />
<el-table-column label="模板名称" align="left" key="name" prop="name"/>
<el-table-column label="导入时间" align="center" key="addTime" prop="addTime"/>
<el-table-column label="编辑时间" align="center" key="upTime" prop="upTime"/>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
<template #default="scope">
<el-button link type="primary" icon="Edit" @click="updateData(scope.row)">编辑</el-button>
<el-button link type="primary" icon="Delete" @click="deleteData(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total > 0"
:total="total"
v-model:page="pageNum"
v-model:limit="pageSize"
@pagination="getDataList"
:page-sizes="[5, 10, 20, 50]"
/>
</div>
</template>
<script setup>
import {onBeforeUnmount, ref} from "vue";
import {ElMessage} from "element-plus";
import {closeWindow, openCenteredWindow, verifyCommand} from "../../openWindow";
import {useRouter} from "vue-router";
import {deletePower, importPower, selectPowerList} from "../../../../api/draw/power";
import LuckyExcel from 'luckyexcel';
const {proxy} = getCurrentInstance();
const router = useRouter();
const dataList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
//查询数据
function getDataList(){
selectPowerList({
pageNum: pageNum.value,
pageSize: pageSize.value
}).then(result => {
dataList.value = result.rows
total.value = result.total
})
}
//删除数据
async function deleteData(row){
if ( await verifyCommand() ){
proxy.$confirm('确定删除吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
let data = {
id: row.id,
}
deletePower(data).then(res=>{
if (res.code === 200){
getDataList()
ElMessage.success('删除成功!');
}else {
ElMessage.error('删除失败')
}
})
}).catch(() => {
proxy.$message({
type: 'info',
message: '取消删除'
});
});
}
}
//编辑按钮
function updateData(row){
router.push({
name: 'excel',
state: {
id: row.id,
title: row.name,
content: row.content,
}
});
}
function handleChangeUpload(file) {
const selectedFile = file.raw;
if (!(selectedFile instanceof File)) {
console.error('传入了非文件对象');
return;
}
if (selectedFile.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
console.log('文件是xlsx类型');
} else {
console.error('不是xlsx文件');
ElMessage.error('请选择xlsx类型文件')
return;
}
let filename = selectedFile.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
let reader = new FileReader();
reader.onload = async (e) => {
let fileData = e.target.result;
try {
LuckyExcel.transformExcelToLucky(fileData, async (exportJson, luckysheetfile) => {
console.log(exportJson.sheets)
//更改配置中的行数为当前最大行
//exportJson.sheets[0].config.rowlen = exportJson.sheets[0].celldata[exportJson.sheets[0].celldata.length-1].r+2
let data = {
name: filename,
content: JSON.stringify(exportJson.sheets)
}
importPower(data).then(res=>{
if (res.code === 200){
getDataList()
ElMessage.success('导入成功')
}else {
ElMessage.error(res.msg)
}
})
});
} catch (e) {
console.error(e);
}
};
reader.onerror = function() {
console.error("File could not be read! Code " + reader.error.code);
};
reader.readAsArrayBuffer(selectedFile);
}
onBeforeUnmount (() => {
closeWindow();
});
// 监听页面即将刷新的事件
window.addEventListener('beforeunload', function (event) {
closeWindow();
});
const goBack = () => {
router.go(-1); // 返回上一页
};
getDataList();
</script>
<style scoped>
</style>
<template>
<div>
<div id="luckysheet" class="luckysheet-wrap"></div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import {ElMessage} from "element-plus";
import {updatePower} from "../../../api/draw/power";
onMounted(() => {
setExcelData();
setExcelStyle();
});
//对表格数据进行渲染
function setExcelData(){
let title = history.state.title;
let content = history.state.content;
const options = {
container: 'luckysheet', // 设定DOM容器的id
title: 'excel 表格', // 设定表格名称
lang: 'zh', // 设定表格语言
hook: {
updated: (e) => {
//监听更新,并在1s后自动保存
$('#luckysheet_info_detail_save').text("已修改")
let title = $('#luckysheet_info_detail_input').val();
let content = luckysheet.getAllSheets();
//去除临时数据,减小体积
for (let i in content)
content[i].data = undefined
}
},
}
options.data = JSON.parse(content)
options.title = title;
window.luckysheet.create(options)
}
//对默认表格的样式进行修改
function setExcelStyle(){
//去除左上角logo
let leftLogo = document.querySelector('.luckysheet-share-logo');
leftLogo.className = '';
//去除左上角返回按钮
let leftButton = document.getElementById('luckysheet_info_detail_title');
leftButton.remove();
// 创建一个新的保存按钮
let newDiv = document.createElement('div');
newDiv.innerHTML = '保存';
newDiv.style.cursor = 'pointer'
newDiv.addEventListener('click', function() {
saveData();
});
let firstChild = document.querySelector('#luckysheet_info_detail').firstElementChild;
document.querySelector('#luckysheet_info_detail').insertBefore(newDiv, firstChild);
}
//保存数据
function saveData(){
let title = $('#luckysheet_info_detail_input').val();
let content = luckysheet.getAllSheets();
//去除临时数据,减小体积
for (let i in content)
content[i].data = undefined
//更改配置中的行数为当前最大行
content[0].config.rowlen = content[0].celldata[content[0].celldata.length-1].r+2
let id = history.state.id
let data = {
id: id,
name: title,
content: JSON.stringify(content)
}
updatePower(data).then(res=>{
if (res.code === 200){
history.state.title = title;
history.state.content = JSON.stringify(content);
ElMessage.success('保存成功!');
}else {
ElMessage.error('保存失败')
}
})
}
</script>
<style scoped>
.luckysheet-wrap {
margin: 0px;
padding: 0px;
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
}
</style>