1. Ideas
Because the project requires excel to be able to preview online, and the excel file is not local but provided by the backend. Therefore, I would like to provide my solution ideas in the project:
1. Let the backend return the binary file stream
2. Convert the file stream into a file object
3. Parse the file object through luckyexcel to get the corresponding data
4. Display the parsed data through luckysheet
2. Installation dependencies
Install luckexcel:
npm i luckyexcel
Install lucksheet , since lukysheet has only two import methods: cdn import and local import, npm is not supported for now, so this article uses local import:
copy all files under the dist folder in the downloaded package to the public directory:
then import dependencies in the index.html file:
3. Code display
1. There must be a container, and given a unique id, it will be used when generating an excel table
2. luckyexcel only supports parsing the data of xlsx files, not xls (you can consider converting xls to 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>
The responseType in the requested interface is blob type to receive the response