vue 实现在线预览excel
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
更新----- luckyexcel 已不再更新,并且已更名为Univer
一、思路
由于项目中要求excel能够在线预览,且excel文件并非本地而是后端那边提供的。因此提供一下本人在项目的解决思路:
1.让后端返回二进制文件流
2.将文件流转为file对象
3.通过luckyexcel解析file对象,得到想对应的数据
4.将解析后得到的数据通过luckysheet进行展示
二、安装依赖
安装luckexcel:
npm i luckyexcel
安装lucksheet,由于lukysheet的引入方式只有两种cdn引入以及本地引入,暂不支持npm,因此此文采用本地引入:
将下载好的包中的dist文件夹下的所有文件复制到public目录下:
然后在index.html文件里引入依赖:
三、代码展示
1.必须要有一个容器,并且给定唯一的id,生成excel表格时会用到
2.luckyexcel只支持解析xlsx文件的数据,不支持xls(可以考虑将xls转换为xlsx)
<template>
<div id="luckysheet" style="margin:0px;padding:0px;width:100vw;height:100vh;"></div>
</template>
<script setup>
import LuckyExcel from "luckyexcel";
import {ElMessage} from "element-plus";
import {downloadFileForData} from '@/modules/api/module1/templateManagement-new'
import {useRoute} from "vue-router";
import {onUnmounted} from "vue";
const route = useRoute()
// 获取excel文件对象,解析成luckysheet可以接受的对象
const handleShowDetail = async () => {
const path = route.params.path.split('/')[0]
try {
const res = await downloadFileForData({
path: path,
filename: route.params.filename
})
// 二进制流(blob)转file对象
const files = new window.File([res], route.params.filename, {type: "application/vnd.ms-excel;charset=utf-8"});
LuckyExcel.transformExcelToLucky(files, exportJson => {
if (!exportJson.sheets || exportJson.sheets.length === 0) {
ElMessage.warning('读取excel文件内容失败');
return;
}
initExcel(exportJson);
})
} catch (e) {
console.log(e)
}
}
// 初始化excel
const initExcel = (exportJson = {}) => {
const name = route.params.filename.split('.')[0]
// eslint-disable-next-line
luckysheet.destroy()
// eslint-disable-next-line
luckysheet.create({
container: 'luckysheet', // luckysheet为容器id
lang: 'zh', //默认语言
title: name,
data: exportJson.sheets //导入excel数据
})
}
// 执行预览excel
handleShowDetail()
onUnmounted(() => {
// eslint-disable-next-line
luckysheet.destroy()
})
</script>
<style scoped>
</style>
请求的接口中的responseType为blob类型接收响应
GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
更多推荐
已为社区贡献4条内容
所有评论(0)